O'Reilly logo

Programmer's Guide to Java™ Certification, A: A Comprehensive Primer, Second Edition by Rolf W. Rasmussen, Khalid A. Mughal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.15. The Conditional Operator: ?

The ternary conditional operator allows conditional expressions to be defined. The operator has the following syntax:

<condition> ? <expression1> : <expression2>

If the boolean expression <condition> is true then <expression1> is evaluated; otherwise, <expression2> is evaluated. Of course, <expression1> and <expression2> must evaluate to values of compatible types. The value of the expression evaluated is returned by the conditional expression.

boolean leapYear = false;
int daysInFebruary = leapYear ? 29 : 28;   // 28

The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left:

(a?b?c?d:e:f:g) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required