W3docs

Java Ternary Operator

Write concise conditional expressions in Java with the ternary operator (condition ? a : b).

The ternary operator ?: is Java's only operator that takes three operands. It's a compact if/else for expressions, not statements — meaning it evaluates to a value you can assign, return, or pass as an argument. This page covers its syntax, where it reads well, the type rules that govern the two branches, and when to reach for if/else or switch instead.

Syntax

condition ? valueIfTrue : valueIfFalse

If condition is true, the whole expression evaluates to valueIfTrue. Otherwise it evaluates to valueIfFalse. Java picks one — and only one — of the two values to compute.

int age = 20;
String status = (age >= 18) ? "adult" : "minor";
System.out.println(status);   // adult

The parentheses around the condition are optional; many style guides recommend them for clarity.

Where it shines

The ternary is at its best for one-shot assignments or as part of a larger expression where an if/else would force you to break the line:

int max = (a > b) ? a : b;
String label = items.isEmpty() ? "no items" : items.size() + " items";
System.out.println("Hello, " + (name != null ? name : "stranger") + "!");

The last form is especially handy: it lets you choose a value inline without introducing a temporary variable.

Types must be compatible

Both branches of a ternary must produce compatible types. The compiler picks the most general common type for the whole expression:

int x = 5;
double d = (x > 0) ? x : 0.0;   // result type is double

Truly incompatible branches — where neither value can be converted to the other and the target type can't accept both — cause a compile error:

// won't compile: String cannot be converted to int
int n = condition ? 1 : "two";

Two unrelated reference types, by contrast, are fine if the target is general enough to hold either result. Here both branches are widened to their common supertype, Object:

Object value = condition ? "yes" : 42;   // 42 is autoboxed to Integer; type is Object

If you specifically need a particular type, cast one branch so the inferred type matches what you expect.

Don't nest deeply

You can nest ternaries — but past one level, they become hard to read:

String grade = (score >= 90) ? "A"
             : (score >= 80) ? "B"
             : (score >= 70) ? "C"
             : "F";

That's borderline; many teams forbid even this. For more than two branches, an if/else if chain or a switch is almost always clearer. Use the ternary when there are exactly two outcomes.

Ternary vs if/else

Both compile to essentially the same bytecode, so it's not a performance choice — it's a readability one. The rules of thumb:

  • Use a ternary when you need a value — assigning, returning, or interpolating.
  • Use if/else when you need statements — side effects, multiple lines, logging.
// good ternary use:
return (errors == 0) ? "OK" : "FAIL";

// bad ternary use — side effects in branches:
boolean ok = (x > 0) ? logSuccess() : logFailure();

The second example does work, but burying side effects inside a conditional expression hides the control flow. Spell it out with if/else.

Null-safe defaults

A common pattern: fall back to a default when something is null:

String displayName = (user.name != null) ? user.name : "Anonymous";

If you find yourself writing this often, the JDK has a helper — Objects.requireNonNullElse:

import java.util.Objects;

String displayName = Objects.requireNonNullElse(user.name, "Anonymous");

A worked example

java— editable, runs on the server

What's next

For dispatching on a single value among many cases, the switch statement is more readable than a long ternary chain. For statement-style branching with side effects, reach for if/else, and see the full set of comparison and logical operators in Java operators.

Practice

Practice
What value does this expression produce when x is 0? x > 0 ? 'positive' : x < 0 ? 'negative' : 'zero'
What value does this expression produce when x is 0? x > 0 ? 'positive' : x < 0 ? 'negative' : 'zero'
Was this page helpful?