Ternary Operator Example in Java

Ternary operator is a conditional operator which has three operands. It is best replacement one-liner for simple if-else statement.

The first operand of ternary operator is a boolean value or expression that returns boolean value. In the next two operands (or statements), either of the operand will be executed based on the value of first  operand.

The below Program illustrates the working principles of ternary operator.

condition?statement1:statement2

Program or Solution

				
				
					

class Ternary

{

public static void main(String args[])

{

int a = 10;

int b = 20;

int c = a>b?a:b;

System.out.println(c);

System.out.println(true?"Decode":"School");

}

}

Output

Ternary Operator Example in Java Output

Program Explanation

In the First println() a is not greater than b so c is 20.

In the second println() first operand is true so it prints "Decode"