Ternary operator in Java
condition ? a : b and its type rules.
true ? 1 : 2.0 prints 1.0, even though the 2.0 branch never runs. How can an unused branch change your result?An if/else that gives a value
condition ? valueIfTrue : valueIfFalse. It's an expression: it produces a value you can store or print.
int a = 7, b = 4;
int max = (a > b) ? a : b; // 7
String s = (a % 2 == 0) ? "even" : "odd";Your turn
What does this print?
int temp = 30;
String w = temp > 25 ? "hot" : "mild";
System.out.println(w);hotmildtrue
Show the answer
temp > 25 is true, so the expression takes the first value: hot.
Only one branch runs
Only the chosen branch is evaluated; the other is skipped completely. That makes guards like this safe:
int x = 0;
int r = (x == 0) ? 0 : 10 / x;
// no division happensBoth branches set the type
The expression's type is decided at compile time from both branches, before anyone knows which will run. Mixed numbers are promoted: an int branch and a double branch make the whole expression a double.
Your turn
What does this print?
System.out.println(true ? 5 : 2.5);
System.out.println(false ? 5 : 2.5);5 2.55.0 2.55.0 2.50
Show the answer
Both expressions have type double, so even the chosen int 5 becomes 5.0. The second picks 2.5.
The unboxing NPE
With an Integer branch and an int branch, the expression's type is int. So cached is unboxed, and unboxing null throws NullPointerException, even though r itself is an Integer.
Integer cached = null;
int fallback = 0;
Integer r = true ? cached : fallback;
// NullPointerException!In real projects
Ternaries are perfect for small choices: labels, defaults, plurals like n == 1 ? "item" : "items". Nesting them three deep is a readability crime most teams reject in code review.
Key takeaways
- max = (a > b) ? a : b;
- Only one branch is evaluated
- Numeric branches are promoted: true ? 1 : 2.0 is 1.0
- Integer vs int branch → unboxing, possible NPE
It's nicknamed "the ternary operator" because it's Java's only operator with three operands. Its official name in the Java spec is the "conditional operator".
Practice questions
What does this print?
int age = 20;
String s = age >= 18 ? "adult" : "minor";
System.out.println(s);- minor
- true
- Compile error
- adult
Check your answer
adult. age >= 18 is true, so the expression takes the first value, "adult".
Which token completes this expression?
int max = (a > b) ___ a : b;- :
- &&
- ->
- ?
Check your answer
?. The ternary operator is written condition ? valueIfTrue : valueIfFalse.