ProgrammingHardProduct-company placement · GATE CS
Which statement about this code is correct?
Which statement about this code is correct?
Object[] arr = new String[2]; // L1 arr[0] = "a"; // L2 arr[1] = Integer.valueOf(1); // L3 List<Object> list = new ArrayList<String>(); // L4
- A. L1 fails to compile because String[] is not an Object[]
- B. Everything compiles, and L3 and L4 both fail at run time
- C. L4 fails to compile; without L4, the code compiles and L3 throws ArrayStoreException at run time
- D. L3 fails to compile because Integer is not a String
Correct answer: C. L4 fails to compile; without L4, the code compiles and L3 throws ArrayStoreException at run time
Arrays are covariant and checked at run time, so L1 and L3 compile but storing an Integer into the real String[] throws ArrayStoreException. Generics are invariant and checked at compile time, so List<String> is not a List<Object>.
More OOP with C++ and Java questions
- What is printed? java int i = 5; i = i++ + ++i; System.out.print(i);
- What is printed? java class A { Object get() { return "A"; } void set(String s) { System.out.print("A.set "); } } class B extends A {…
- What is printed? java Long a = 1L; System.out.print(a.equals(1) + " " + a.equals(1L) + " " + (a == 1));
- What is printed? cpp struct B { B() { f(); } virtual ~B() { f(); } virtual void f() { cout << "B"; } }; struct D : B { D() { f(); } ~D() {…
- What is printed? cpp struct M { int id; M(int i) : id(i) { cout << "M" << id; } ~M() { cout << "m" << id; } }; struct B { B() { cout <<…
- What is printed? cpp struct C { static int n; C() { ++n; } C(const C&) { ++n; } ~C() { --n; } }; int C::n = 0; void f(C c) { cout << C::n…