The Ternary Operator <code>?:</code> in Java
The ternary operator ?: is the only operator in Java that takes three operands. It evaluates a boolean condition and returns one of two values depending on the outcome. Unlike if/else, it's an expression β useful inside assignments, method arguments, and return statements.
Syntax
result = condition ? valueIfTrue : valueIfFalse;
Examples
String s = active ? "ON" : "OFF";
int abs = n >= 0 ? n : -n;
return user == null ? "anon" : user.name();
send(amount > 0 ? amount : 0);
Type rules
The two result expressions must share a common type. For references the result is the nearest common supertype; for primitives Java applies numeric promotion:
Object o = cond ? "string" : 42; // β
common type is Object
int n = cond ? 1 : 2.0; // β different β would need a cast
double x = cond ? 1 : 2.0; // β
1 is promoted to double
Autoboxing pitfall
Integer boxed = null;
int prim = cond ? boxed : 0; // NPE if cond is true β unboxes null
If one branch is a primitive and the other is a wrapper, Java unboxes the wrapper β and null crashes.
Chains are usually a mistake
// β hard to read
var label = score > 90 ? "A" : score > 80 ? "B" : score > 70 ? "C" : "F";
// β
switch expression (Java 14+)
var label = switch ((int) score / 10) {
case 10, 9 -> "A";
case 8 -> "B";
case 7 -> "C";
default -> "F";
};
Optional replaces many null-ternaries
String name = user != null ? user.name() : "anon";
// With Optional
String name = Optional.ofNullable(user).map(User::name).orElse("anon");
Common mistakes
- Nested ternaries β switch to
if/elseor aswitchexpression after one level. - Autoboxing NPE β match the types of both branches.
- Side effects in the branches β ternaries are expressions, not control flow. Keep them pure.
Related
Pillar: Java control flow. See also operators: ternary, switch expression.