ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
class A {
    static int x = f();
    static int y = 10;
    static int f() { return y * 2; }
}
// in main:
System.out.print(A.x + " " + A.y);
  1. A. 20 10
  2. B. 0 10
  3. C. 0 0
  4. D. Compile error: illegal forward reference

Correct answer: B. 0 10

Static initialisers run in textual order. When x = f() runs, y still has its default value 0, so x = 0; then y becomes 10. Reading y inside a method is not an illegal forward reference; only a direct use of y in x's initializer would be.

More OOP with C++ and Java questions

Exams that ask this topic