Ternary Operator in Java

In the post conditional operators in Java we talked about the Conditional-AND and Conditional-OR operators, here we’ll talk about another conditional operator known as ternary operator in Java (?:).

Ternary operator uses three operands thus the name ternary operator and it can be used in place of if-else statement or switch-case statement to make code more compact and readable.

Java ternary operator syntax

Ternary operator in Java has the following form-

result = boolean_expression ? Operand2 : Operand3

First operand is always a boolean expression returning either true or false. If the boolean expression is true then the evaluation of Operand2 is assigned to result, if the expression is false then the evaluation of Operand3 is assigned to result.

Ternary operator Java example

As already said ternary operator can be used in place of if-else statement to make the code more compact.
For example the following if-else statement-

can be written using ternary operator in Java as follows-

Nested ternary operator

Ternary operator in Java can be nested too though it makes it a little less readable.

For example the following if-else statement-

can be written using ternary operator as follows-

That’s all for the topic Ternary Operator in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.