ProgrammingHardProduct-company interview pattern
What happens when this Java code is compiled and run?
What happens when this Java code is compiled and run?
Object o = new ArrayList<String>();
List<String> l = (List<String>) o;
String s = (String) o;
System.out.print("done");- A. Compilation error at the third line
- B. It compiles; a ClassCastException is thrown at the third line
- C. It prints done
- D. ClassCastException at the second line
Correct answer: B. It compiles; a ClassCastException is thrown at the third line
Casting from Object to String is a legal downcast, so it compiles; at run time the object is an ArrayList, not a String, so the cast throws ClassCastException. The cast to List<String> succeeds (it only gives an unchecked warning).
More OOP with C++ and Java questions
- What is printed? cpp struct A { A() { cout << "D"; } A(const A&) { cout << "C"; } A& operator=(const A&) { cout << "="; return this; } }…
- What is printed? java String s = "b"; switch (s) { case "a": System.out.print("A"); case "b": System.out.print("B"); case "c"…
- What happens when this Java code is compiled? java try { FileReader r = new FileReader("a.txt"); } catch (Exception e) {…
- This class is meant to be immutable. What change is still needed? java public final class Team { private final List<String> members…
- What is printed? cpp struct V { int x; V(int a) : x(a) {} V operator+(const V& o) const { return V(x + o.x 2); } }; int main() { V a(1)…
- 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…