1Z0-811 · Question #55
Given: public class Test { int var1; // line n1 public static void main (String[] args) { int var2; // line n2 Test obj = new Test(); int var3 = var2 - obj.var1; System.out.println (var3); } } What…
The correct answer is B. Compilation fails. To make it compile, replace line n2 with var2 = 0. Option B is correct because var2 is a local variable declared inside main(), and Java requires local variables to be explicitly initialized before use - the compiler will not assign a default value. Since var2 is used in var2 - obj.var1 without ever being assigned, the code…
Question
Options
- ACompilation fails. To make it compile, replace line n1 with var1 = 0;
- BCompilation fails. To make it compile, replace line n2 with var2 = 0;
- C0
- DNothing is printed.
How the community answered
(28 responses)- B89% (25)
- C7% (2)
- D4% (1)
Explanation
Option B is correct because var2 is a local variable declared inside main(), and Java requires local variables to be explicitly initialized before use - the compiler will not assign a default value. Since var2 is used in var2 - obj.var1 without ever being assigned, the code fails to compile; replacing line n2 with var2 = 0; gives it an initial value and fixes the error.
Option A is wrong because var1 is an instance variable (a field on the class), and Java automatically initializes instance variables to their default values (0 for int) - no manual initialization is needed, and no compile error occurs there.
Options C and D are both wrong for the same reason: the code never compiles, so it never runs and there is no output at all - "0" and "nothing is printed" both describe runtime outcomes, not a compile failure.
Memory tip: Think "Local = You must initialize, Instance = Java initializes." If a variable is declared inside a method (local), the compiler demands you set it first. If it's a field on a class (instance/static), Java quietly sets it to zero/null/false for you.
Topics
Community Discussion
No community discussion yet for this question.