ProgrammingVery hardProduct-company placement · Java
What is printed?
What is printed?
class P { static int v = 5; static { System.out.print("P"); } }
class C extends P { static { System.out.print("C"); } }
// in main:
System.out.print(C.v);- A. P5
- B. PC5
- C. CP5
- D. 5
Correct answer: A. P5
A static field reference initialises only the class that DECLARES the field. v belongs to P, so C's static block never runs even though the code says C.v.
More OOP with C++ and Java questions
- What is printed? java class C { static { System.out.print("init "); } } // in main: C[] a = new C[2]; Class<?> k = C.class…
- What is printed? java try { try { System.out.print("1"); throw new Exception("a"); } catch (Exception e) { System.out.print("2"); throw…
- What happens when this is compiled (inside a method declared throws IOException)? java List<String> files = List.of("a.txt")…
- Which line fails to compile? java List<?> l = new ArrayList<String>(); l.add(null); // L1 l.add("x"); // L2 Object o = l.isEmpty() ? null…
- Which line fails to compile? java class Fruit implements Comparable<Fruit> { public int compareTo(Fruit o) { return 0; } } class Apple…
- Which line fails to compile? java // Java 16 or later Object o = "hello"; if (o instanceof String s && s.length() > 3)…