What is Ternary Operator in JAVA

The Java ternary operator, being the sole conditional operator with three operands, offers a concise syntax as an alternative to the if..else statement, effectively compiling into an equivalent if-else statement with identical functionality.

condition ? trueStatement : falseStatement
  1. Condition : First part is the condition section.
  2. trueStatement : Second is the code block which executes in case of first part condition goes true.
  3. falseStatement : The Third part code block executes if condition results as false.

A ternary operator in Java employs the ? and : symbols, where the first operand is a boolean expression. If the expression evaluates to true, the second operand's value is returned; otherwise, the value of the third operand is returned. This construct is frequently utilized when a variable's value depends on the truthfulness of a specific boolean expression.

The following Java program evaluate a condition using if..else statement.

int x = 20, y = 10; if (x>y) System.out.println("x is greater than y"); else System.out.println("x is less than or equal to y");

The same, we can do with ternary operator in java.

int x = 20, y = 10; String result = x > y ? "x is greater than y" : "x is less than or equal to y";
Full Source
public class TestClass { public static void main(String[] args) { int x = 20, y = 10; String result = x > y ? "x is greater than y" : "x is less than or equal to y"; System.out.println(result); } } //Output:x is greater than y

Nested Ternary Operator

You can use Ternary Operator in nested statement like in if..else condition.

Nested if else example
public class TestClass { public static void main(String[] args) { int x=10; int y=20; int z=30; if( x > y ) { if ( x > z ){ System.out.println("x is greatest") ; } else{ System.out.println("z is greatest") ; } } else{ if ( y > z ){ System.out.println("y is greatest") ; } else{ System.out.println("z is greatest") ; } } } } //Output: z is greatest
Nested Nested Ternary Operator Example
public class TestClass { public static void main(String[] args) { int x=10; int y=20; int z=30; String result = x > y ? x > z ? "x is greatest" : "z is greatest" : y > z ? "y is greatest" : "z is greatest"; System.out.println(result) ; } } //Output: z is greatest

Conclusion

The ternary operator in Java allows for concise conditional expressions, where the value of a variable depends on the evaluation of a boolean expression.