skip to content

What is the ternary conditional operator (?:) in Java, and how does it work?

level: juniorimportance: must knowfreq 70%

answer

  1. Three operands: condition ? a : b
  2. It's an expression — produces a value
  3. Only the chosen branch is evaluated (short-circuit)
  4. Right-associative → chains like else-if
  5. Condition must be boolean (Boolean is unboxed)

basics

~20 s

It's a one-line if/else that produces a value. You write condition ? a : b: if the condition is true you get a, otherwise b. It's an expression, so its result can be assigned or returned.

solid answer

~40 s

The ternary (conditional) operator is Java's only three-operand operator: condition ? whenTrue : whenFalse. The condition must be a boolean (or Boolean, which is unboxed). It is an expression, not a statement, so it evaluates to a value you can assign, return, or pass as an argument. Exactly one of the two branches is evaluated (short-circuit), so side effects in the unused branch never run. It is right-associative, so a ? b : c ? d : e parses as a ? b : (c ? d : e), which naturally chains like else-if. Compared to an if/else statement, it keeps simple value-selection concise, but nesting it deeply hurts readability, and unlike if/else both branches must produce a value of a compatible type because the whole expression has a single result type.

code

java · 11 lines
java
int a = 3, b = 7;
int max = (a > b) ? a : b;   // max == 7

// expression, so usable inline and chainable
String size = max == 0 ? "empty"
            : max == 1 ? "single"
            : "many";

// only the chosen branch runs:
int[] arr = null;
int len = (arr == null) ? 0 : arr.length; // arr.length never evaluated -> no NPE

go deeper

for a junior

Can read and write a simple ternary and explain it as a one-line if/else that returns a value.

for a middle

Knows it is an expression, that only one branch is evaluated, and that it is right-associative so it chains like else-if; uses it for clean value selection.

for a senior

Articulates when NOT to use it (side effects, deep nesting), and that the condition unboxes a Boolean and the result has a single common type.

for a principal

Frames readability/maintainability trade-offs for teams, sets style guidance (e.g. discourage nested ternaries), and connects the single-result-type rule to promotion/boxing hazards covered elsewhere.

## What it is An **operator** is a symbol that combines values to produce a new value (like `+` or `<`). An **operand** is one of the inputs to an operator. Most Java operators take one or two operands; the **ternary conditional operator** is the only one that takes **three**, which is why it is often just called "the ternary operator." Its syntax is: ``` condition ? valueIfTrue : valueIfFalse ``` ## Statement vs expression A **statement** is a complete instruction that *does* something (e.g. an `if` block). An **expression** is something that *evaluates to a value* (e.g. `2 + 3`). The key fact about the ternary operator is that it is an **expression**: the whole thing produces a single value. That means you can do things you cannot do with a plain `if`: ```java int max = (a > b) ? a : b; // assign the result return (x == null) ? "none" : x; // return the result log("size=" + (n == 1 ? "one" : "many")); // use it inline ``` ## How evaluation works 1. The **condition** is evaluated first. It must be a `boolean`. If it is the wrapper type `Boolean`, Java automatically **unboxes** it (converts the object to the primitive). If that `Boolean` is `null`, unboxing throws a `NullPointerException`. 2. If the condition is `true`, **only** `valueIfTrue` is evaluated. If it is `false`, **only** `valueIfFalse` is evaluated. The other branch is **never** evaluated — this is called **short-circuit** evaluation. So side effects (like a method call or `i++`) in the skipped branch do not happen. 3. The result of the chosen branch becomes the value of the whole expression. ## Associativity **Associativity** is the rule for how operators of equal precedence group when there are several in a row. The ternary operator is **right-associative**, meaning it groups from the right: ```java String grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"; // parses as: score>=90 ? "A" : (score>=80 ? "B" : (score>=70 ? "C" : "F")) ``` This is why chained ternaries read like an `if / else if / else` ladder. ## When to use it Use it for **simple value selection** where an `if/else` would be verbose. Avoid it when the branches have side effects or when nesting more than one or two levels deep — it quickly becomes unreadable, and that is exactly when a plain `if/else` is clearer. ## Subtleties to know later Because the whole expression has *one* result type, Java must compute a **common type** for the two branches. This pulls in numeric promotion and autoboxing rules that can produce surprising results (including `NullPointerException` from auto-unboxing) — those are covered in the type-promotion question.

  • Is the unused branch of a ternary evaluated?
    No. Exactly one branch is evaluated depending on the condition, so side effects in the other branch never run — just like the not-taken half of an if/else.
  • Can a ternary be used as a statement on its own line?
    No. It is an expression and must produce a value that is used (assigned, returned, passed). Writing it as a bare statement is not valid Java; use an if statement for pure side effects.

Think of a fork in a road with a single sign: the sign reads the condition and points you down exactly one path. You only ever walk one path, and wherever the chosen path leads is the single answer you bring back.

saying these in an interview costs you the question

  • Claiming both branches are always evaluated (they are not — it short-circuits)
  • Calling it a statement; it is an expression
  • Thinking the condition can be any type — it must be boolean/Boolean
  • Saying it is left-associative (it is right-associative)

context