ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
class T {
    static int a = T.b + 1;
    static int b = 5;
    static int c = b + 1;
}
// in main:
System.out.print(T.a + " " + T.b + " " + T.c);
  1. A. 1 5 6
  2. B. 6 5 6
  3. C. It does not compile (illegal forward reference)
  4. D. 1 5 1

Correct answer: A. 1 5 6

Static initialisers run in textual order. Using the simple name b before its declaration would be an illegal forward reference, but the qualified name T.b is allowed, and at that point b still has its default value 0. So a = 1, then b = 5, then c = b + 1 = 6.

More OOP with C++ and Java questions

Exams that ask this topic