Multiple choice technology programming languages

What is the output for the below code ? public class Test { public static void main(String argv[]){ ArrayList list = new ArrayList(); ArrayList listStr = list; ArrayList listBuf = list; listStr.add(0, "Hello"); StringBuffer buff = listBuf.get(0); System.out.println(buff.toString()); } }

  1. Hello

  2. Compile error

  3. java.lang.ClassCastException

  4. null

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

The raw ArrayList (no type parameter) can hold any object. When we add a String to it, it compiles due to backward compatibility. However, when we retrieve it through listBuf (typed as ArrayList), the runtime cannot enforce the type - it returns the actual object (String) and attempts to cast it to StringBuffer, causing ClassCastException. This demonstrates why mixing raw and generic types is unsafe.

AI explanation

java.lang.ClassCastException is correct. list is declared as a raw ArrayList, so assigning it to both ArrayList listStr and ArrayList listBuf compiles with only unchecked-conversion warnings (no compile error) because raw types bypass generics checking. At runtime, listStr.add(0, "Hello") inserts an actual String into the shared underlying list. When listBuf.get(0) is called, the compiler inserts an implicit cast to StringBuffer (due to type erasure, the generic type isn't checked at the get() call itself but at the assignment), and casting the String "Hello" to StringBuffer fails at run-time, throwing ClassCastException.