ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class A {
    static int x = init("x", 1);
    static { System.out.print("sA "); }
    static int y = init("y", 2);
    static int init(String n, int v) { System.out.print(n + " "); return v; }
}
public class Main {
    public static void main(String[] args) {
        System.out.print(A.x + " ");
    }
}
  1. A. sA x y 1
  2. B. x y sA 1
  3. C. x sA y 1
  4. D. 1 x sA y

Correct answer: C. x sA y 1

Static fields and static blocks run once, in textual top-to-bottom order, the first time the class is actively used (A.x triggers it here). init("x",1) runs first printing 'x', then the static block prints 'sA', then init("y",2) prints 'y' — only afterward is A.x read and printed as 1.

More OOP with C++ and Java questions

Exams that ask this topic