🌱BeginnerControl Flow

Ternary Operator

Write concise conditional expressions with Java's ternary operator: condition ? valueIfTrue : valueIfFalse.

Overview

The ternary operator (also called the conditional operator) is a compact way to write a simple if/else that produces a value. It takes three operands: a condition, a value to use if the condition is true, and a value to use if it is false. Syntax: condition ? valueIfTrue : valueIfFalse The ternary is an expression, not a statement - it returns a value that you can assign to a variable, pass to a method, or print directly. Use it for simple one-liner decisions. For anything more complex, stick with a regular if/else.

Key Points

  • •Syntax: condition ? valueWhenTrue : valueWhenFalse
  • •Returns a value - can be used inside expressions, assignments, and method calls
  • •Both branches must produce compatible types (both int, both String, etc.)
  • •Perfect for simple value selection: `max = a > b ? a : b;`
  • •Nested ternaries are legal but reduce readability - prefer if/else for complex logic
  • •The condition must be a boolean expression, exactly like in if statements

Examples

Basic ternary usage

public class Main {
    public static void main(String[] args) {
        int age = 20;

        // if/else version
        String status;
        if (age >= 18) {
            status = "Adult";
        } else {
            status = "Minor";
        }

        // Ternary version - same result, one line
        String status2 = age >= 18 ? "Adult" : "Minor";

        System.out.println(status);   // Adult
        System.out.println(status2);  // Adult
    }
}

Both produce identical results. The ternary is appropriate here because the logic is simple and the result is one of two strings.

Ternary in method calls and expressions

public class Main {
    public static void main(String[] args) {
        int a = 15, b = 9;

        // In a println directly
        System.out.println("Max: " + (a > b ? a : b)); // Max: 15

        // Absolute value
        int n = -42;
        int abs = n >= 0 ? n : -n;
        System.out.println("Abs: " + abs);  // 42

        // Assign different types based on condition
        double score = 72.5;
        String grade = score >= 90 ? "A" : score >= 70 ? "B" : "C or below";
        System.out.println("Grade: " + grade); // Grade: B
    }
}

The nested ternary `... ? "A" : score >= 70 ? "B" : "C or below"` is acceptable for 2-3 levels max.

When NOT to use ternary

// OK - simple, clear
boolean isEven = n % 2 == 0;
String label = isEven ? "even" : "odd";

// BAD - too complex for ternary, use if/else
String result = a > b ? (b > c ? "A biggest" : (a > c ? "A biggest" : "C biggest")) : "other";

// BETTER as if/else:
String result2;
if (a > b && a > c) {
    result2 = "A biggest";
} else if (b > c) {
    result2 = "B biggest";
} else {
    result2 = "C biggest";
}

If you need to nest ternaries more than one level deep, switch to if/else.

Common Mistakes

  • Trying to execute statements (System.out.println) in a ternary - ternary expects values/expressions, not statements
  • Mixing incompatible types: `int x = flag ? 1 : "no"` - one is int, the other String, causes a compile error
  • Overusing ternary for clarity - a simple one-level ternary is fine; nested ternaries quickly become unreadable

Note

The ternary operator is also called the "conditional operator". A good rule of thumb: if the ternary fits on one line and is immediately clear, use it. If you need to think about it, use if/else.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

What does `int result = x > 0 ? 1 : -1;` produce when x = 5?