Phase 3 of 20 · Topic 3.4

Ternary Operator & Expression Evaluation

1Concept

The ternary operator condition ? expr1 : expr2 offers inline conditional assignment. In Java 8+, ternary expressions support target typing and auto-unboxing rules.

2Architecture Diagram

Condition (score >= 50) ---> [ True ] ---> Result: "PASS"
                        ---> [ False] ---> Result: "FAIL"

3Code Example

Core Java
public class TernaryDemo {
    public static void main(String[] args) {
        int mark = 88;
        String result = (mark >= 90) ? "Distinction" :
                        (mark >= 75) ? "First Class" : "Pass";
        System.out.println("Result: " + result);
    }
}

4Expected Output

Result: First Class

5Key Takeaways

  • Avoid deep nesting of ternary operators to maintain clean code readability.
  • Watch out for NullPointerException when mixing primitive and Wrapper types in ternary expressions.
  • Ternary expressions MUST return a value; they cannot execute void statements.