Java Reference ยท Operators
The Java conditional operator ?:
Reference for Java's conditional (ternary) operator ?: with examples: the result type rules, unboxing NullPointerException traps, nesting and style.
The conditional operator ?:, usually called the ternary operator because it takes three operands, chooses between two expressions. It evaluates the condition; if it is true the result is the second operand, otherwise the third. Only the chosen branch is evaluated.
Because it is an expression, you can use it where a value is needed: in an assignment, a method argument or a return. For choosing between statements, use if/else.
String label = count == 1 ? "item" : "items";
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
condition ? valueIfTrue : valueIfFalse
| Operand | Description |
|---|---|
condition |
A boolean (or Boolean) expression |
valueIfTrue |
Evaluated and returned only when the condition is true |
valueIfFalse |
Evaluated and returned only when the condition is false |
Usage notes
- Right-associative.
a ? b : c ? d : emeansa ? b : (c ? d : e). Chains of more than two levels are better written asif/else ifor aswitchexpression. - Type rules. If both operands are numeric, the result gets the promoted type (
intanddoublegivedouble). If both arebooleanor both references, the result has that type. Mixed cases may box or find a common supertype. Be careful:cond ? 1 : 2.0prints1.0. - Unboxing trap. If one branch is a primitive and the other a wrapper, the wrapper is unboxed.
cond ? nullInteger : 0throwsNullPointerExceptionwhen the first branch is chosen. Make both branches the same wrapper type, or avoidnull. - Not a statement.
cond ? doA() : doB();is rejected unless the value is used. Useif. - Low precedence, above assignment and below
||. Parenthesize when concatenating:"x" + (n > 0 ? "a" : "b"). - Switch expressions (Java 14+) are often clearer for several cases; see switch.
- Lambda or method reference branches need a target type:
Runnable r = cond ? () -> a() : () -> b();works, butvar r = ...does not.
Related
- if and else, switch, Logical operators, Operator precedence
- Lessons: if and else, Switch