In Java, what will be the output of the following program (note the use of pre-increment and short-circuit OR)? class Test { public static void main(String [] args) { int x = 0; int y = 0; for (int z = 0; z < 5; z++) { if ((++x > 2) || (++y > 2)) { x++; } } System.out.println(x + " " + y); } }
-
A5 3
-
B8 2
-
C8 3
-
D8 5
-
ENone of the above
Answer
Correct Answer: 8 2
Explanation
Introduction / Context:This problem tests short-circuit OR (||) behavior with pre-increment. With OR, once the left operand is true, the right operand is not evaluated.
Given Data / Assumptions:
- x = 0, y = 0 initially.
- Condition: (++x > 2) || (++y > 2).
- If true, x++ inside the if-block.
- Loop runs 5 times.
Concept / Approach:For ||, if the left-hand side becomes true, the right-hand side is skipped (no ++y). Therefore ++y happens only while (++x > 2) is still false.
Step-by-Step Solution:
Iter 1: ++x = 1 → left false → evaluate ++y = 1 → false → no body → x = 1, y = 1.Iter 2: ++x = 2 → left false → evaluate ++y = 2 → false → no body → x = 2, y = 2.Iter 3: ++x = 3 → left true → right skipped → if-body x++ → x = 4, y = 2.Iter 4: ++x = 5 → left true → right skipped → if-body x++ → x = 6, y = 2.Iter 5: ++x = 7 → left true → right skipped → if-body x++ → x = 8, y = 2.Verification / Alternative check:Instrument the loop with prints for x and y on each iteration to validate the sequence.
Why Other Options Are Wrong:They assume y keeps increasing after left-hand side becomes true, ignoring short-circuit OR.
Common Pitfalls:Not realizing that once (++x > 2) becomes true, (++y > 2) never executes again in later iterations.
Final Answer:8 2