O'Reilly logo

Java, A Beginner’s Guide, 5th Edition by Herbert Schildt

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

The ? Operator

One of Java’s most fascinating operators is the ?. The ? operator is often used to replace if-else statements of this general form:

if (condition)

var = expression1;

else

var = expression2;

Here, the value assigned to var depends upon the outcome of the condition controlling the if.

The ? is called a ternary operator because it requires three operands. It takes the general form

Exp1? Exp2: Exp3;

where Exp1 is a boolean expression, and Exp2 and Exp3 are expressions of any type other than void. The type of Exp2 and Exp3 must be the same (or compatible), though. Notice the use and placement of the colon.

The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value ...

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