ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
class P {
static { System.out.print("1"); }
{ System.out.print("2"); }
P() { System.out.print("3"); }
}
class C extends P {
static { System.out.print("4"); }
{ System.out.print("5"); }
C() { this(0); System.out.print("6"); }
C(int k) { System.out.print("7"); }
}
// in main:
new C();
new C();- A. 142357623576
- B. 14235576235576
- C. 142376523765
- D. 14235761423576
Correct answer: A. 142357623576
Static initialisers run once, when each class is first initialised, parent first: 1 then 4. For each object, C() begins with this(0), so it does not call super itself; C(int) does (implicitly). Instance initialisers of C run right after the super() call, i.e. only inside C(int). So each object prints P's initialiser 2, P() 3, C's initialiser 5, C(int) 7, and finally the rest of C() 6: 23576. Running the initialiser in both constructors gives 5 twice; repeating the static blocks for the second object is the other trap.
More OOP with C++ and Java questions
- What is printed? java class P { P() { show(); } void show() { } } class C extends P { final int a = 5; int b = 7; final String s = "s"…
- 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()…