nerdexam
Oracle

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.

Using Operators and Decision Constructs

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)
  • A
    3% (1)
  • C
    75% (27)
  • D
    14% (5)
  • E
    6% (2)
  • F
    3% (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.

A-6

This would be the result if `var3` was assigned `var1`'s final value, or if `var2` was decremented twice before assignment.

B-4

This would be the result if `var3` was assigned `var2`'s value *after* `var2` was incremented to -4.

C-5Correct

`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.

D5

This implies an incorrect calculation or sign change.

E4

This implies an incorrect calculation or sign change.

FCompilation fails

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

#operators#increment/decrement#conditional statements#side effects

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice