The Ternary Operator
condition ? a : b.
What Is the Ternary Operator?
The ternary operator is Java's only operator that takes three operands. It is a compact way to choose between two values based on a condition.
Its shape is: condition ? valueIfTrue : valueIfFalse.
It produces a value, so you can assign it or pass it directly.
int age = 20;
String status = age >= 18 ? "adult" : "minor";The Three Parts
The first part is a boolean condition. The ? separates it from the results.
If the condition is true, the expression evaluates to the part before :. If false, it evaluates to the part after :.
Only one of the two branches is actually evaluated.
int score = 45;
String result = score >= 50 ? "pass" : "fail";All lessons in this course
- The Ternary Operator
- Nesting Ternaries
- Ternary vs if/else
- Readability Pitfalls