In Java (control flow with i++ and --j inside a do-while), what are the final values printed? int i = 1, j = 10; do { if(i++ > --j) /* Line 4 / { continue; } } while (i < 5); System.out.println("i = " + i + " and j = " + j); / Line 9 */

Difficulty: Medium

Correct Answer: i = 5 and j = 6

Explanation:


Introduction / Context:
This problem exercises short, precise reasoning about post-increment and pre-decrement inside a conditional, plus the behavior of continue within a do-while loop. Understanding evaluation order is crucial to get the final values correct.


Given Data / Assumptions:

  • Start with i = 1, j = 10.
  • Condition checks i++ (returns old i, then increments) and --j (decrements then returns).
  • continue skips to the while-condition check at the loop bottom.


Concept / Approach:
Trace each iteration carefully and update i and j in the exact order the expression evaluates: left operand i++ first (post-increment), right operand --j second (pre-decrement), then compare. The body has no other state changes except potential continue (which still executes the loop condition afterward).


Step-by-Step Solution:

Iter1: i++ yields 1 → i=2; --j yields 9 → compare 1>9 false; condition i<5 true (i=2) Iter2: i++ yields 2 → i=3; --j yields 8 → 2>8 false; i<5 true Iter3: i++ yields 3 → i=4; --j yields 7 → 3>7 false; i<5 true Iter4: i++ yields 4 → i=5; --j yields 6 → 4>6 false; i<5 now false (i=5) → exit


Verification / Alternative check:
Because the if-condition never becomes true, continue never fires; only the implicit increments from the condition update i and j each time. Final: i = 5, j = 6.


Why Other Options Are Wrong:

  • Other pairs assume a different number of iterations or reversed increment/decrement order.


Common Pitfalls:
Forgetting that i++ returns the old value while still incrementing afterward; and that --j decrements before comparison.


Final Answer:
i = 5 and j = 6

More Questions from Java.lang Class

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion