Ternary Operator in Java

Ternary operator works like a concise form of if-else statement.


Syntax

Its general form is :

As the name suggests, it takes three arguments. All three are expressions.

  • expr1 must be a boolean expression i.e. it must evaluate to either true or false.
  • expr2 and expr3 must be type compatible with each-other i.e. they must evaluate to the same data type. (They need not be a boolean expression)

This is how it works:

  • If expr1 evaluates to true, expr2 is evaluated and returned.
  • Else expr3 is evaluated and returned.

The returned value may be assigned to a variable or returned from a method depending on the requirements..


An Example

The output is:

The same identical output would be generated by the following line of code using if-else statement.

Note that ternary operator did the same thing in more compact way.


Nesting ternary operators

Like if-else statement, ternary operator can be nested very easily. See the example below:

The output is:

Note that:

  • Ternary operator associates right to left. So both lines below are identical. Second one uses parenthesis to make its point clear:

 

  • The same output can be generated using if-else statement :

  • Notice how compact was the ternary operator compared to the corresponding if-else code.
  • But it was hard to read and understand the code quickly. Nesting  upto 2 levels is good after that code becomes unreadable.

If-else vs Ternary Operator

If else statement in general can be re-written using nested ternary operators. But don’t over do it, after two levels code becomes hard to understand. Consider the following code:

The corresponding code using ternary operator would be:

Even if you use parenthesis the code is very much unreadable.


Miscellaneous topics

  • If the expr1 evaluates to true, expr2 is evaluated and returned, expr3 is left untouched.
  • If the expr1 evaluates to false, expr3 is evaluated and returned, expr2 is left untouched.

The output is :

Explanation: Since 5 is greater than 10, x>y evaluates to false. So ++x is not executed and ++y is executed.