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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access