Concept Flow - Ternary operator
Evaluate condition
Yes/No
True
Return true_value
Result
The ternary operator checks a condition and returns one of two values depending on whether the condition is true or false.
int a = 10; int b = 20; int max = (a > b) ? a : b; System.out.println(max);
| Step | Condition (a > b) | Result of Condition | Value chosen | max value |
|---|---|---|---|---|
| 1 | 10 > 20 | false | b (20) | 20 |
| 2 | Print max | - | - | 20 |
| Variable | Start | After Step 1 | After Step 2 |
|---|---|---|---|
| a | 10 | 10 | 10 |
| b | 20 | 20 | 20 |
| max | undefined | 20 | 20 |
Ternary operator syntax: condition ? value_if_true : value_if_false; It evaluates the condition once. Returns value_if_true if condition is true. Returns value_if_false if condition is false. Used for simple conditional assignments. Example: int max = (a > b) ? a : b;