ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
class K {
    static final int C = 10;
    static final Integer D = 20;
    static { System.out.print("K "); }
}
// in main:
System.out.print(K.C + " ");
System.out.print(K.D + " ");
System.out.print(K.C);
  1. A. K 10 20 10
  2. B. 10 K 20 10
  3. C. 10 20 10
  4. D. K 10 K 20 K 10

Correct answer: B. 10 K 20 10

K.C is a constant variable (static final int with a constant initialiser), so the compiler copies 10 into main; reading it does not initialise class K. K.D is final but of type Integer, which is not a constant, so reading it is a real field access that triggers K's initialisation - its static block prints 'K ' before the value 20 is printed. The class is initialised only once, and the last K.C is again inlined.

More OOP with C++ and Java questions

Exams that ask this topic