ProgrammingHardWipro · Cognizant pattern
What happens when this line is compiled?
What happens when this line is compiled?
List<String>[] arr = new List<String>[10];
- A. It compiles and creates an array of 10 empty String lists
- B. Compile-time error: generic array creation is not allowed
- C. It compiles but throws ArrayStoreException on first write
- D. It compiles with an unchecked warning only
Correct answer: B. Compile-time error: generic array creation is not allowed
Java forbids creating an array of a parameterized type directly, because arrays are reified (they remember their element type at run time) while generics are erased; allowing new List<String>[10] would let code bypass generics' type safety through an array store. It is a hard compile-time error, not just a warning.
More OOP with C++ and Java questions
- What is printed? java class A { static void who() { System.out.print("A"); } } class B extends A { static void who() {…
- What is printed? java class K { int a, b; K(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return 1; } public boolean…
- What is printed? java class Counter { private int count = 0; void inc() { count++; } int get() { return count; } } class LoggingCounter…
- What is printed? java String a = "hel" + "lo"; String b = "hello"; System.out.println(a == b);
- Which statement about this code is correct? java class P { P(int x) { System.out.print("P" + x + " "); } } class C extends P { C() {…
- What is printed? cpp struct Base { virtual void show() { cout << "Base "; } }; struct Derived : Base { void show() override { cout <<…