Ternary Operator in Java – The ? : operator

(Last Updated On: February 25, 2019)

Ternary operator java example with simple program – Ternary operator in java (also known as ? : operator) is a conditional operator and it can be used in place of if-else statement in java programs to write as one liner statement.

 

Syntax of ternary operator is as ” Condition ? 1st statement : 2nd statement” . “Condition” is the Boolean expression, and if condition is true then 1st statement will be evaluated or else 2nd statement will be evaluated. It is called ternary operator as it takes 3 operands i.e. Condition, 1st statement and 2nd statement.

 

Below is the simple program example using if else statement and using ternary operator in java program with same output.

 

Java ternary operator example :

Output:
result using if else condition : a is less than b
result using ternary operator : a is less than b