ProgrammingVery hardProduct-company placement · Java
What is printed?
What is printed?
class Util { static int say(String s) { System.out.print(s); return 1; } }
interface I { int X = Util.say("I"); }
class C implements I { static { System.out.print("C"); } }
// in main:
new C();
System.out.print(C.X);- A. ICI1
- B. CI1
- C. IC1
- D. C1
Correct answer: B. CI1
Initialising a class does not initialise its superinterfaces unless they declare default methods, so new C() prints only C. X is not a compile-time constant, so reading it (even as C.X) initialises I, which prints I first.
More OOP with C++ and Java questions
- What is printed? java class P { static int v = 5; static { System.out.print("P"); } } class C extends P { static { System.out.print("C")…
- 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…