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 : First part is the condition section.
- trueStatement : Second is the code block which executes in case of first part condition goes true.
- 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
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
Output
z is greatest
Nested Nested Ternary Operator Example
Output
z is greatest