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.
Table of Contents
Understanding the Ternary Operator in Java
variable = (condition) ? value_if_true : value_if_false;
Syntax Breakdown
- Condition: Expression returning
true
orfalse
. - 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
- Keep it simple – Use only for basic conditions.
- Use parentheses – Improve clarity, e.g.,
(x > y) ? x : y
. - Prioritize readability – If code becomes messy, switch to
if-else
.