? :
Picks one of two values by a condition — a short form of if-else.
Available since: Java 1.0
Syntax
condition ? valueIfTrue : valueIfFalseExamples
Choosing a value:
void main() {
int age = 20;
String status = age >= 18 ? "adult" : "minor";
IO.println(status);
int count = 1;
IO.println(count + (count == 1 ? " item" : " items"));
}Output:
adult
1 itemNotes
The ternary operator is an expression and has a value; if is a statement. Nested ternaries are hard to read — for three or more cases a switch expression is better. When combined with string concatenation, wrap the ternary in parentheses.
See also
In the tutorial
- Conditions — Branching in Java: if, else, else if, compound conditions and the ternary operator.