☕ Java

Ternary Operator

The ternary operator is Java's only three-operand operator. It's a compact conditional expression that returns one of two values based on a boolean condition. Used correctly, it makes code more concise. Overused or nested, it makes code unreadable.

Syntax and Basic Usage

The ternary operator has three parts: a condition, a value if true, and a value if false. The result is always one of the two value expressions.
Java
// Syntax:
// condition ? valueIfTrue : valueIfFalse

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

// Equivalent if-else:
String status2;
if (age >= 18) {
    status2 = "adult";
} else {
    status2 = "minor";
}

// The ternary is an EXPRESSION — it returns a value:
// if-else is a STATEMENT — it executes code
// This means ternary can be used inline:
System.out.println(age >= 18 ? "adult" : "minor");  // directly in method call
int abs = x >= 0 ? x : -x;                          // inline assignment

Type Rules

The type of a ternary expression is determined by the types of its two value branches. Java must be able to find a common type for both branches.
Java
// Both branches same type — result is that type:
int a = 5, b = 3;
int max = a > b ? a : b;   // both int — result is int

// Different numeric types — widened to larger type:
int i = 5;
double d = 3.14;
double result = true ? i : d;   // i widened to double — result is double

// One branch null — type is the non-null branch's type:
String s = condition ? "Hello" : null;   // result type is String

// Both branches are numeric literals — special rules apply:
// byte b = true ? 1 : 2;   — valid: both literals fit in byte
// byte b2 = true ? 1 : 200; — valid: 200 fits in byte? No — COMPILE ERROR

// Object types — result is common ancestor:
Object o = condition ? "string" : 42;   // String and Integer — result is Object

// Autoboxing in ternary — be careful with null:
Integer value = condition ? 42 : null;
int x = condition ? 42 : null;   // NullPointerException if condition is false!
// Because: int x = (int)(Integer)null — unboxing null throws NPE

Where Ternary Shines

The ternary operator is most valuable for concise conditional assignments and inline values. These are the patterns where it genuinely improves readability.
Java
// Conditional assignment — cleaner than if-else for simple cases:
int score = 85;
String grade = score >= 90 ? "A"
             : score >= 80 ? "B"
             : score >= 70 ? "C"
             : "F";

// Default value — when a value might be null:
String username = getUsername();
String display = username != null ? username : "Guest";

// Absolute value:
int abs = n >= 0 ? n : -n;

// Min and max:
int min = a < b ? a : b;
int max = a > b ? a : b;

// Inline in method calls — avoids temp variable:
System.out.println("You have " + count + " message" + (count == 1 ? "" : "s"));
// prints "You have 1 message" or "You have 5 messages"

// Conditional formatting:
String label = isEnabled ? "Enabled" : "Disabled";
String color = isPrimary ? "#007BFF" : "#6C757D";

// Logging — only compute expensive message if needed (combined with &&):
logger.debug("Result: " + (result != null ? result.toString() : "null"));

Nested Ternary — Use with Caution

Ternary operators can be nested — one branch can itself be a ternary expression. This enables multi-way conditional expressions, but readability degrades quickly beyond two levels.
Java
// Two-level nesting — borderline readable with formatting:
int score = 75;
String grade = score >= 90 ? "A"
             : score >= 80 ? "B"
             : score >= 70 ? "C"
             : score >= 60 ? "D"
             : "F";
System.out.println(grade);  // "C"

// Associativity — ternary is right-associative:
// a ? b : c ? d : e  is parsed as  a ? b : (c ? d : e)
// So the grade example works correctly

// Three levels — becoming unreadable:
String result = a > b ? (a > c ? "a" : "c") : (b > c ? "b" : "c");
// This finds the largest of a, b, c — but is it immediately clear?

// DON'T — deeply nested ternary:
String msg = x > 0 ? x > 10 ? x > 100 ? "huge" : "big" : "medium" : "small";
// Unreadable — use if-else or a method

// DO — use if-else or extract a method for complex logic:
String classify(int x) {
    if (x > 100) return "huge";
    if (x > 10)  return "big";
    if (x > 0)   return "medium";
    return "small";
}

Ternary vs if-else — When to Use Which

The ternary operator and if-else aren't interchangeable in all cases. Here's when to use each:
Java
// ── USE TERNARY when: ────────────────────────────────────────────

// 1. Choosing between two VALUES (not executing statements):
String label = isActive ? "Active" : "Inactive";

// 2. Inline in an expression or method call:
System.out.printf("Found %d item%s%n", n, n == 1 ? "" : "s");

// 3. Simple, obvious conditions with short values:
int fee = isPremium ? 0 : 10;


// ── USE IF-ELSE when: ─────────────────────────────────────────────

// 1. Executing statements (not just selecting values):
if (isValid) {
    save(data);
    notifyUser();
} else {
    showError("Invalid data");
    logFailure();
}
// Can't do this with ternary — ternary must be an expression

// 2. More than two branches (use if-else-if or switch):
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else grade = "F";

// 3. Complex conditions that hurt readability as ternary:
// Ternary (hard to read):
String msg = user != null && user.isActive() && user.hasRole("ADMIN")
    ? "Welcome, Admin" : "Access Denied";
// if-else (clearer):
String msg2;
if (user != null && user.isActive() && user.hasRole("ADMIN")) {
    msg2 = "Welcome, Admin";
} else {
    msg2 = "Access Denied";
}