ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
class P {
    P() { show(); }
    void show() { }
}
class C extends P {
    final int a = 5;
    int b = 7;
    final String s = "s";
    final Integer n = 9;
    void show() {
        System.out.print(a + " " + b + " " + s + " " + n + " | ");
    }
}
// in main:
new C().show();
  1. A. 0 0 null null | 5 7 s 9 |
  2. B. 5 0 s null | 5 7 s 9 |
  3. C. 5 7 s 9 | 5 7 s 9 |
  4. D. 5 0 null null | 5 7 s 9 |

Correct answer: B. 5 0 s null | 5 7 s 9 |

P() calls the overridden show() before C's field initialisers have run, so ordinary fields still hold defaults: b = 0 and n = null. But a and s are constant variables (final, of primitive or String type, initialised with a constant expression); the compiler replaces every use of them with the value itself, so they print 5 and s even at that early point. n is final but of type Integer, which is not a constant type, so it is still null. The second call, after construction, prints all real values.

More OOP with C++ and Java questions

Exams that ask this topic