Ternary Operator in Java with Examples: Ternary Operator vs. if...else Statement

The ternary operator is Java's only conditional operator that takes three operands, making it a compact shorthand for simple if...else logic. It's written using ? and :.

Syntax

variable = (condition) ? valueIfTrue : valueIfFalse;

Basic Example

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

Equivalent if...else Statement

int age = 20;
String status;
if (age >= 18) {
    status = "Adult";
} else {
    status = "Minor";
}
System.out.println(status);

Ternary Operator vs if...else Statement

  • The ternary operator is an expression that returns a value; if...else is a statement that controls program flow
  • Ternary is best for short, simple conditions assigned to a variable; if...else is better for multiple statements or complex logic
  • Ternary expressions can be nested, but doing so often hurts readability compared to a clear if...else chain
  • Both evaluate the same condition logic — the choice mainly comes down to code clarity and use case

Nested Ternary Example

int marks = 75;
String grade = (marks >= 90) ? "A" : (marks >= 75) ? "B" : "C";
Use the ternary operator for quick, single-value decisions, but switch to if...else once your logic involves multiple conditions or actions, since deeply nested ternaries become hard to read.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course

The Ternary Must Produce a Value

Because the ternary operator is an expression, Java expects its result to be used somewhere: assigned, returned or passed to a method. Writing it as a standalone statement does not compile.

int age = 20;

// age >= 18 ? System.out.println("Adult") : System.out.println("Minor");  // compile error
System.out.println(age >= 18 ? "Adult" : "Minor");                          // correct

static String fee(boolean isStudent) {
    return isStudent ? "Discounted" : "Standard";   // directly in a return
}

Only one of the two branches is evaluated. That makes the ternary handy for safe defaults, because the risky branch never runs when the condition rules it out:

String first = (list != null && !list.isEmpty()) ? list.get(0) : "empty";

Type Rules That Surprise People

Java works out one result type for the whole expression from both branches. This leads to two well-known surprises.

Numeric promotion

Object o = true ? 1 : 2.0;
System.out.println(o);   // prints 1.0, not 1

Since one branch is a double, the int branch is promoted to double as well, even though it is the branch that ran.

Hidden unboxing and NullPointerException

Map<String, Integer> stock = new HashMap<>();
boolean known = true;

Integer qty = known ? stock.get("pen") : 0;   // throws NullPointerException

One branch is an Integer and the other is the primitive int 0, so the expression type becomes int. Java tries to unbox the null returned by get and fails. Fix it by keeping both sides as objects, or avoid the ternary here altogether:

Integer qty1 = known ? stock.get("pen") : Integer.valueOf(0);   // no unboxing
int qty2 = stock.getOrDefault("pen", 0);                       // clearer

Picking Between Ternary, if...else and switch

SituationBest fit
Choose between two values for one variableTernary
Run several statements or call methods with side effectsif...else
Map one value to many possible resultsswitch expression
Check ranges like marks or agesif...else if chain

Modern Java's switch expression also returns a value, which makes it a cleaner replacement for long nested ternaries when you compare one variable against fixed values:

String type = switch (day) {
    case "SAT", "SUN" -> "Weekend";
    default -> "Weekday";
};

Readability Habits and Common Slips

  • Wrap the condition in parentheses even when it is not required; it makes the expression easier to scan.
  • Keep both branches short. If a branch needs a method call with side effects, use if...else.
  • If you nest, put each level on its own line so the structure is visible.
  • Do not mix primitive and wrapper types in the two branches without thinking about unboxing.
  • Do not use the ternary only to return true or false; return x > 0; is simpler than return x > 0 ? true : false;.

Quick test for yourself: what does System.out.println(false ? 1 : 'A'); print? Both branches are numeric-compatible, and because 1 is a constant that fits in a char, the result type is char, so it prints A.