Java programming — Nested conditional (ternary) operator evaluation: class Test { public static void main(String [] args) { int x=20; String sup = (x < 15)? "small" : (x < 22)? "tiny" : "huge"; System.out.println(sup); } }
Java Programming
Operators and Assignments
Difficulty: Easy
Choose an option
-
Asmall
-
Btiny
-
Chuge
-
DCompilation fails
Answer
Correct Answer: tiny
Explanation
Introduction / Context:This checks understanding of nested ternary operators and left-to-right evaluation of conditions.
Given Data / Assumptions:
- x = 20.
- Expression form: cond1 ? A : (cond2 ? B : C).
Concept / Approach:Evaluate the first condition. If false, evaluate the second condition in the nested ternary. The chosen string is then printed.
Step-by-Step Solution:
Check x < 15: 20 < 15 is false, so move to nested ternary.Check x < 22: 20 < 22 is true, so result is "tiny".Prints tiny.Verification / Alternative check:Rewrite using if/else to confirm: if (x < 15) "small"; else if (x < 22) "tiny"; else "huge".
Why Other Options Are Wrong:"small" would require x < 15; "huge" would require x >= 22; no compilation issues here.
Common Pitfalls:Misgrouping nested ternary operators or forgetting that they are right-associative.
Final Answer:tiny