ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
class T {
static int a = T.b + 1;
static int b = 5;
static int c = b + 1;
}
// in main:
System.out.print(T.a + " " + T.b + " " + T.c);- A. 1 5 6
- B. 6 5 6
- C. It does not compile (illegal forward reference)
- D. 1 5 1
Correct answer: A. 1 5 6
Static initialisers run in textual order. Using the simple name b before its declaration would be an illegal forward reference, but the qualified name T.b is allowed, and at that point b still has its default value 0. So a = 1, then b = 5, then c = b + 1 = 6.
More OOP with C++ and Java questions
- What is printed? java class K { static final int C = 10; static final Integer D = 20; static { System.out.print("K "); } } // in main…
- Which lines fail to compile? java interface I { static String id() { return "I"; } default String name() { return "N"; } } class C…
- What is printed? cpp struct B { virtual string who() const { return "B"; } }; struct D : B { string who() const override { return "D"; }…
- What is printed? cpp struct M { M() { cout << "m"; } ~M() { cout << "~m"; } }; struct B { B() { cout << "b"; f(); } virtual ~B() { cout <<…
- What is printed? cpp struct P { P(const char s) { cout << s; } }; struct B1 { B1() { cout << "1"; } }; struct B2 { B2() { cout << "2"; }…
- What is printed? cpp struct A { A() { } A(const A&) { cout << "C"; } A& operator=(const A&) { cout << "="; return this; } }; void f(A a) {…