1Z0-803 · Question #247
Given the code fragment int var1 = -5; int var2 = var1--; int var3 = 0; if (var2 < 0) { var3 = var2++; } else { var3 = --var2; } System.out.println(var3); What is the result?
The correct answer is C. -5. This question tests understanding of Java's pre-increment/decrement and post-increment/decrement operators within an if/else block. The final printed value of var3 is determined by the evaluation order of these operators.
Question
Given the code fragment int var1 = -5; int var2 = var1--; int var3 = 0; if (var2 < 0) { var3 = var2++; } else { var3 = --var2; } System.out.println(var3); What is the result?
Options
- A-6
- B-4
- C-5
- D5
- E4
- FCompilation fails
How the community answered
(36 responses)- A3% (1)
- C75% (27)
- D14% (5)
- E6% (2)
- F3% (1)
Why each option
This question tests understanding of Java's pre-increment/decrement and post-increment/decrement operators within an if/else block. The final printed value of `var3` is determined by the evaluation order of these operators.
This would be the result if `var3` was assigned `var1`'s final value, or if `var2` was decremented twice before assignment.
This would be the result if `var3` was assigned `var2`'s value *after* `var2` was incremented to -4.
`var1--` assigns `var1`'s current value (-5) to `var2` before `var1` is decremented to -6. The `if (var2 < 0)` condition evaluates to true because `var2` is -5. Inside the if block, `var2++` assigns `var2`'s current value (-5) to `var3` before `var2` is incremented to -4, resulting in `var3` being -5.
This implies an incorrect calculation or sign change.
This implies an incorrect calculation or sign change.
The code fragment is syntactically correct and will compile.
Concept tested: Java increment/decrement operator precedence
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Topics
Community Discussion
No community discussion yet for this question.