Java : Ternary/Conditional Operator

The Ternary Operator also knew as Conditional Operator. If this logical expression result is true then only block or statements of expression1 will execute otherwise control will reach to expression2.

Ternary operator is equivalent to if-else statement If this logical expression execution result is true then only the block associated with if statement will execute otherwise control will reach to else block.

Ternary Operator or conditional Operator

Note: Ternary operators use when need to reduce the number of line of code for better readability.

See Also :

Ternary Operator Example

In this example, the ternary operator uses to decide the category of a person based on age. another example is to decide odd or even number.

public class TernaryOperatorTest {

	public static void main(String[] args) {
		//age test
		int age =25;

		String ageCategory=age<18? "Minor" : "Adult";
		System.out.println("Category for Age :" + age +" is"+ ageCategory );

		//Odd even test
		int number=50;
		boolean isEven= number%2==0 ? true: false;

		System.out.println("Number :" + 50 +" is even "+ isEven );



Category for Age :25 isAdult
Number :50 is even true