ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement
What is printed?
What is printed?
class A {
static int x = f();
static int y = 10;
static int f() { return y * 2; }
}
// in main:
System.out.print(A.x + " " + A.y);- A. 20 10
- B. 0 10
- C. 0 0
- D. Compile error: illegal forward reference
Correct answer: B. 0 10
Static initialisers run in textual order. When x = f() runs, y still has its default value 0, so x = 0; then y becomes 10. Reading y inside a method is not an illegal forward reference; only a direct use of y in x's initializer would be.
More OOP with C++ and Java questions
- What is printed? java class P { P() { show(); } void show() { System.out.print("P"); } } class C extends P { int v = 7; String s = "x"…
- Which statement about this code is correct? java try { new java.io.FileReader("a.txt").close(); } catch (java.io.IOException | Exception…
- What is printed? java class A { void m(A a) { System.out.print("AA"); } } class B extends A { void m(A a) { System.out.print("BA"); } void…
- Which lines fail to compile? java List<Integer> ints = new ArrayList<>(); List<Number> a = ints; // line 1 List<? extends Number> b =…
- What happens? java boolean flag = true; Integer none = null; Integer r1 = flag ? null : 0; System.out.print(r1); Integer r2 = flag ? none…
- What is printed? java System.out.print(Math.abs(Integer.MINVALUE) + " "); System.out.print(Integer.MAXVALUE + 1 == Integer.MINVALUE);