Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Operators

The Java conditional operator ?:

Reference for Java's conditional (ternary) operator ?: with examples: the result type rules, unboxing NullPointerException traps, nesting and style.

The conditional operator ?:, usually called the ternary operator because it takes three operands, chooses between two expressions. It evaluates the condition; if it is true the result is the second operand, otherwise the third. Only the chosen branch is evaluated.

Because it is an expression, you can use it where a value is needed: in an assignment, a method argument or a return. For choosing between statements, use if/else.

Java
String label = count == 1 ? "item" : "items";

Try it

Java Choosing a value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Result types and the unboxing trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
condition ? valueIfTrue : valueIfFalse
Operand Description
condition A boolean (or Boolean) expression
valueIfTrue Evaluated and returned only when the condition is true
valueIfFalse Evaluated and returned only when the condition is false

Usage notes

  • Right-associative. a ? b : c ? d : e means a ? b : (c ? d : e). Chains of more than two levels are better written as if/else if or a switch expression.
  • Type rules. If both operands are numeric, the result gets the promoted type (int and double give double). If both are boolean or both references, the result has that type. Mixed cases may box or find a common supertype. Be careful: cond ? 1 : 2.0 prints 1.0.
  • Unboxing trap. If one branch is a primitive and the other a wrapper, the wrapper is unboxed. cond ? nullInteger : 0 throws NullPointerException when the first branch is chosen. Make both branches the same wrapper type, or avoid null.
  • Not a statement. cond ? doA() : doB(); is rejected unless the value is used. Use if.
  • Low precedence, above assignment and below ||. Parenthesize when concatenating: "x" + (n > 0 ? "a" : "b").
  • Switch expressions (Java 14+) are often clearer for several cases; see switch.
  • Lambda or method reference branches need a target type: Runnable r = cond ? () -> a() : () -> b(); works, but var r = ... does not.