What is the output of the following Java code? int m = 1000; int k = 3000;…
2021
What is the output of the following Java code?
int m = 1000;
int k = 3000;
while (++m < --k);
System.out.println(m);Answer: C. 2000 — Concept — pre-increment and the empty statement In Java, ++x is a pre-increment: the variable is updated first, and every comparison inside that same…
- A.
Error
- B.
1000
- C.
2000
- D.
4000
Attempted by 358 students.
Show answer & explanation
Correct answer: C
Concept — pre-increment and the empty statement
In Java, ++x is a pre-increment: the variable is updated first, and every comparison inside that same expression uses the already-updated value. A semicolon written immediately after while (condition) is an empty statement, and that empty statement becomes the loop body — so such a loop does no work of its own; it simply keeps re-evaluating its condition until the condition turns false.
Applying it to this program
Start with
m = 1000andk = 3000.Before every comparison,
++mraises m by 1 and--klowers k by 1. Both updates happen inside the same check.So one check moves m and k one step towards each other, and the sum m + k never changes: it stays 1000 + 3000 = 4000.
After n checks, m = 1000 + n and k = 3000 - n.
The loop repeats while m < k, that is 1000 + n < 3000 - n, which simplifies to 2n < 2000, so n < 1000. The first 999 checks are therefore true.
On check number 1000, m = 2000 and k = 2000, and 2000 < 2000 is false, so the loop ends. m has already been raised to 2000 by that very check.
Cross-check
Trace the first two checks and the last one:
Check n | m after | k after | Is m < k ? |
|---|---|---|---|
1 | 1001 | 2999 | true |
2 | 1002 | 2998 | true |
999 | 1999 | 2001 | true |
1000 | 2000 | 2000 | false |
k fell by exactly 1000 while m rose by exactly 1000, so both land on 2000 and the sum is still 4000 — the two routes agree.
Result
The empty body changes nothing else, so System.out.println(m) prints 2000.
Note that the semicolon does not stop the loop after a single pass; it only removes the body. The condition on its own keeps the loop running.