1Z0-811 · Question #66
Given the code fragment: int a = 3; a = ++a + a++; a = --a - a--; System.out.println (a); What is the output?
The correct answer is C. 0. Option C (0) is correct because tracing both assignments carefully yields zero. First, a = ++a + a++ with a=3: ++a pre-increments a to 4 (value used: 4), then a++ post-increments using the current value of 4 (value used: 4, a briefly becomes 5), giving 4 + 4 = 8, so a = 8. Then…
Question
Options
- A8
- B4
- C0
- DA compilation error occurs.
How the community answered
(36 responses)- A6% (2)
- B11% (4)
- C64% (23)
- D19% (7)
Explanation
Option C (0) is correct because tracing both assignments carefully yields zero. First, a = ++a + a++ with a=3: ++a pre-increments a to 4 (value used: 4), then a++ post-increments using the current value of 4 (value used: 4, a briefly becomes 5), giving 4 + 4 = 8, so a = 8. Then a = --a - a-- with a=8: --a pre-decrements a to 7 (value used: 7), then a-- post-decrements using the current value of 7 (value used: 7), giving 7 - 7 = 0, so a = 0.
A (8) is wrong because it only accounts for the first assignment and ignores the second. B (4) likely comes from misapplying operator precedence or incorrectly computing the subtraction step. D is wrong because Java compiles this without error - unlike C/C++, Java guarantees left-to-right evaluation of operands, so multiple side effects in one expression are defined behavior.
Memory tip: Think "Pre = Prepare first" (change the value before using it) and "Post = Postpone" (use the current value then change it). Trace one operator at a time, updating a after each step, and always complete the full expression before assigning the result back.
Topics
Community Discussion
No community discussion yet for this question.