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();- A. 0 0 null null | 5 7 s 9 |
- B. 5 0 s null | 5 7 s 9 |
- C. 5 7 s 9 | 5 7 s 9 |
- 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
- What is printed? java // static methods of the main class: static int f() { int x = 1; try { x = 2; throw new IllegalStateException(); }…
- What is printed? java Long l = 127L; Integer i = 127; System.out.print(l.equals(127) + " "); System.out.print(l.equals(127L) + " ")…
- What is printed? java // static methods of the main class: static void f(long x) { System.out.print("long "); } static void f(Integer x) {…
- What happens when this code runs? java List<String> strs = new ArrayList<>(); strs.add("a"); List raw = strs; raw.add(42)…
- What is printed? java final String a = "Ja"; String b = "Ja"; String x = a + "va"; String y = b + "va"; String z = y.intern()…
- What is printed? java class K { int id; K(int id) { this.id = id; } public boolean equals(Object o) { return o instanceof K && ((K) o).id…