nerdexam
Oracle

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

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 main(String args[]) { Test test = new Test(); } } What is the result?

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)
  • A
    11% (3)
  • B
    4% (1)
  • C
    81% (22)
  • E
    4% (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):

  1. Static initializers run at class-load time, before any instance exists → y = 3
  2. Instance field initializers and instance initializer blocks execute in textual order after super(), before the constructor body → x = 1, then x = 2
  3. Constructor body runs last → prints x (which is 2) and y (which is 3)

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.

Full 1Z0-819 Practice