ProgrammingHardTCS NQT · Infosys interview pattern

What is printed?

What is printed?
class A {
    int x = 10;
    A() { x = 20; }
    { x = 30; }
}
// in main:
System.out.print(new A().x);
  1. A. 30
  2. B. 10
  3. C. 20
  4. D. Compilation error

Correct answer: C. 20

Field initialisers and instance initialiser blocks run in textual order (x = 10, then x = 30) right after super(), and only then does the rest of the constructor body run (x = 20). The block’s position after the constructor in the source does not matter.

More OOP with C++ and Java questions

Exams that ask this topic