Ternary Operator in Java

The ternary operator in Java (?:) lets us write compact if-else logic in a single line. We can use it to simplify decision-making in Java without sacrificing readability.

Understanding the Ternary Operator in Java

variable = (condition) ? value_if_true : value_if_false;  

Syntax Breakdown

  • Condition: Expression returning true or false.
  • True value: Assigned if the condition is met.
  • False value: Assigned otherwise.

Practical Examples

1. Basic Use

Replace

if (score > 50) {  
    result = "Pass";  
} else {  
    result = "Fail";  
}  

With

result = (score > 50) ? "Pass" : "Fail";  

2. Nested Ternary

Complex

int discount = (age < 12) ? 50 : (age > 60) ? 30 : 10;  

When to Use the Ternary Operator

  • Simple conditions: Ideal for straightforward true/false checks.
  • Inline assignments: Assign values directly in return statements or variable declarations.
  • Avoid: Complex logic or nested structures that reduce readability.

Key Best Practices

  1. Keep it simple – Use only for basic conditions.
  2. Use parentheses – Improve clarity, e.g., (x > y) ? x : y.
  3. Prioritize readability – If code becomes messy, switch to if-else.

Sharing Is Caring: