ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class A {
static int x = init("x", 1);
static { System.out.print("sA "); }
static int y = init("y", 2);
static int init(String n, int v) { System.out.print(n + " "); return v; }
}
public class Main {
public static void main(String[] args) {
System.out.print(A.x + " ");
}
}- A. sA x y 1
- B. x y sA 1
- C. x sA y 1
- D. 1 x sA y
Correct answer: C. x sA y 1
Static fields and static blocks run once, in textual top-to-bottom order, the first time the class is actively used (A.x triggers it here). init("x",1) runs first printing 'x', then the static block prints 'sA', then init("y",2) prints 'y' — only afterward is A.x read and printed as 1.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual void f() { std::cout << "Base "; } }; struct Mid : Base { }; struct Derived : Mid { void f()…
- What is printed? cpp struct Base { Base(){ std::cout << "Base "; } }; struct Mem { Mem(){ std::cout << "Mem "; } }; struct Derived : Base…
- What is printed? cpp struct A { virtual void f() { std::cout << "A::f "; } }; struct B : A { void f() override { std::cout << "B::f "; }…
- Which statement about this program's behaviour is true? cpp struct S { int b; int a; S() : a(1), b(a + 1) { } }; int main() { S s…
- What is printed? java class A { protected int val() { return 1; } } class B extends A { protected int val() { return 2; } } class C…
- A Java class's constructor runs this.handle = acquire(); and then later throws an exception before returning. Which statement is correct?