SiteMap  | About    

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.

  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.

The same, we can do with ternary operator in java

Full Source


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


z is greatest

Nested Nested Ternary Operator Example


z is greatest (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.