➗ Operators & Expressions · Beginner

Ternary operator in Java

condition ? a : b and its type rules.

🧩 The mysterytrue ? 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";
🔮 Predict it

Your turn

What does this print?

int temp = 30;
String w = temp > 25 ? "hot" : "mild";
System.out.println(w);
  1. hot
  2. mild
  3. true
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 happens

Both 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.

🔮 Predict it

Your turn

What does this print?

System.out.println(true ? 5 : 2.5);
System.out.println(false ? 5 : 2.5);
  1. 5 2.5
  2. 5.0 2.5
  3. 5.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 trap

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 the real world

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

  1. max = (a > b) ? a : b;
  2. Only one branch is evaluated
  3. Numeric branches are promoted: true ? 1 : 2.0 is 1.0
  4. Integer vs int branch → unboxing, possible NPE
🤯 Did you know?

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);
  1. minor
  2. true
  3. Compile error
  4. 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;
  1. :
  2. &&
  3. ->
  4. ?
Check your answer

?. The ternary operator is written condition ? valueIfTrue : valueIfFalse.

Next: who goes first, && or ||? * or +? Precedence decides, and getting it wrong changes your answer.