What is Ternary Operator in JAVA

Java ternary operator is the only conditional operator that takes three operands. It is a conditional operator that provides a shorter syntax for the if..else statement. They compile into the equivalent if-else statement, meaning they will be exactly the same.
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 uses ? and : symbols. The first operand is a boolean expression; if the expression is true then the value of the second operand is returned otherwise the value of the third operand is returned. The value of a variable often depends on whether a particular Boolean expression is or is not true.

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