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);- A. 30
- B. 10
- C. 20
- 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
- What is printed? java interface I { default String who() { return "I"; } } class P { public String who() { return "P"; } } class C extends…
- What is printed? java StringBuilder a = new StringBuilder("hi"); StringBuilder b = new StringBuilder("hi"); System.out.print(a.equals(b) +…
- What happens when this Java code is compiled and run? java Object o = new ArrayList<String>(); List<String> l = (List<String>) o; String s…
- What is printed? cpp struct A { A() { cout << "D"; } A(const A&) { cout << "C"; } A& operator=(const A&) { cout << "="; return this; } }…
- What is printed? java String s = "b"; switch (s) { case "a": System.out.print("A"); case "b": System.out.print("B"); case "c"…
- What happens when this Java code is compiled? java try { FileReader r = new FileReader("a.txt"); } catch (Exception e) {…