One of Java’s most fascinating operators is the ?. The ? operator is often used to replace if-else statements of this general form:
var = expression1;
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 ...