0Pricing
Java Academy · Lesson

Nesting Ternaries

Chain decisions carefully.

What Is a Nested Ternary?

A nested ternary places another ternary inside one of its branches.

This lets you choose between three or more outcomes instead of just two.

The result is a chain of conditions, evaluated from left to right.

int score = 75;
String grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";

How It Groups

The ternary is right-associative. That means the false branch swallows the rest of the chain.

So a ? x : b ? y : z reads as a ? x : (b ? y : z).

Each : hands off to the next condition.

// reads as: a ? x : (b ? y : z)
String r = false ? "x" : true ? "y" : "z"; // r = "y"

All lessons in this course

  1. The Ternary Operator
  2. Nesting Ternaries
  3. Ternary vs if/else
  4. Readability Pitfalls
← Back to Java Academy