JavaTernary Operator

Ternary Operator

The ternary operator (?:) is Java’s only operator that takes three operands, which is where its name comes from. It is a compact, expression-based alternative to a simple if-else statement — instead of executing one of two blocks of code, it evaluates to one of two values.

Syntax

Java
condition ? valueIfTrue : valueIfFalse

Java evaluates condition first. If it is true, the whole expression evaluates to valueIfTrue; if it is false, the whole expression evaluates to valueIfFalse. Exactly one of the two value expressions is ever evaluated, never both.

A Compact Alternative to if-else

Compare these two equivalent pieces of code:

Using if-else

Java
String status;
if (age >= 18) {
    status = "adult";
} else {
    status = "minor";
}

Using the ternary operator

Java
String status = (age >= 18) ? "adult" : "minor";

Both versions produce the same result, but the ternary version expresses “pick one of two values” in a single line, which reads naturally when the sole purpose of the if-else is to assign a value.

Worked Example: Finding the Maximum of Two Numbers

MaxFinder.java

Java
public class MaxFinder {
    public static void main(String[] args) {
        int a = 15;
        int b = 42;

        int max = (a > b) ? a : b;

        System.out.println("The larger number is: " + max);
    }
}
The larger number is: 42

Here, (a > b) is the condition. Since 15 > 42 is false, the expression evaluates to b, and 42 is assigned to max.

Nesting Ternary Operators

Because the ternary operator produces a value, you can nest one ternary expression inside another to check multiple conditions:

Java
int score = 82;

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

System.out.println(grade); // B
Nested Ternaries Hurt Readability
A single ternary expression is usually easy to read at a glance. Nested or chained ternaries, like the grade example above, get harder to parse quickly the more conditions you add — and they only get worse if someone edits one branch without noticing the surrounding structure. For anything beyond one level of nesting, most style guides recommend switching to a regular `if-else` chain or a `switch` expression, which is easier to scan and modify safely.
  • Use the ternary operator for simple, single-condition value selection — especially in assignments, return statements, and method arguments.

  • Avoid nesting more than one level deep; prefer if-else or switch once logic gets that complex.

  • Both branches of a ternary should generally produce compatible types, since the overall expression has a single type.

Note
The ternary operator is often called the “conditional operator” in the Java Language Specification — both names refer to the exact same `?:` syntax.