The Ternary Operator in Java β <code>? :</code>
The ternary operator is Java's one and only three-operand operator: condition ? valueIfTrue : valueIfFalse. It's an expression (returns a value), so you can use it anywhere an expression is allowed β assignments, arguments, return statements.
Basic
String status = active ? "ON" : "OFF";
int abs = n >= 0 ? n : -n;
return user != null ? user.name() : "anonymous";
Types must be compatible
Object x = cond ? "string" : 42; // β
compiles β common type is Object
int x = cond ? 1 : "s"; // β no common type
Autoboxing trap
Integer a = null;
int x = cond ? a : 0; // NPE if cond is true β unboxes null
Mixing a wrapper and a primitive in the two branches forces unboxing on every path.
When to prefer if/else
- Either branch has side effects.
- Either branch is more than a short expression.
- You're nesting ternaries β readability collapses fast.
// β unreadable
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";
};
"Elvis" operator? Java doesn't have one
Kotlin's a ?: b ("take a, or b if a is null") doesn't exist in Java. The ternary is the closest equivalent:
String name = user != null ? user.name() : "anon";
String name = Optional.ofNullable(user).map(User::name).orElse("anon"); // cleaner for chains
Common mistakes
- Nested ternaries β hard to read, easy to break. Switch to
if/elseor aswitchexpression. - Autoboxing NPE β see above.
- Using a ternary just to be terse β if it's slower to read, it's the wrong choice.
Related
Pillar: Java operators. See also if/else, switch.