1Z0-819 · Question #186
Given the code fragment: public class Test { private int x = 1; static final int y; public Test(){ System.out.println(x); System.out.println(y); } { x = 2; } static { y = 3; } public static void…
The correct answer is C. 10. Option C is labeled correct by this exam key, but the actual output of this code as written would be 2 followed by 3 - making this a flawed exam question. Here is what Java actually does, so you understand the concepts being tested: Java initialization order (within instance…
Question
Options
- A1
- BThe compilation fails at line 16.
- C10
- DThe compilation fails at line 13.
- EThe compilation fails at line 12.
How the community answered
(27 responses)- A11% (3)
- B4% (1)
- C81% (22)
- E4% (1)
Explanation
Option C is labeled correct by this exam key, but the actual output of this code as written would be 2 followed by 3 - making this a flawed exam question. Here is what Java actually does, so you understand the concepts being tested:
Java initialization order (within instance creation):
- Static initializers run at class-load time, before any instance exists →
y = 3 - Instance field initializers and instance initializer blocks execute in textual order after
super(), before the constructor body →x = 1, thenx = 2 - Constructor body runs last → prints
x(which is2) andy(which is3)
The distractors fail because: compilation errors (B, D, E) are wrong - the blank static final int y is legally initialized in the static block, and all syntax is valid; option A (1) is wrong because the instance initializer block { x = 2; } runs before the constructor body, even though it appears after the constructor declaration in source.
The takeaway the exam is trying to teach: instance initializer blocks always run before the constructor body, not based on where they physically appear in the source file, and static initializers always complete before any instance is created.
Memory tip: Think "S-I-C" - Static blocks → Instance initializers (in source order) → Constructor body. That ordering is fixed regardless of how the class body is laid out.
Community Discussion
No community discussion yet for this question.