Here is a scenario that has confused many Java developers, because the line that crashes contains no cast at all. Look at this program and predict what it does.
import java . util . ArrayList ; import java . util . List ;
public class TrickyDemo { public static void main ( String [ ] args ) { List < Integer > numbers = new ArrayList <> ( ) ; numbers . add ( 1 ) ;
List raw = numbers ; // hand the same list to a raw-typed reference raw . add ( "not a number" ) ; // compiles, believe it or not
for ( Integer n : numbers ) { System . out . println ( "got " + n ) ; // no cast written anywhere here } } }
Enter fullscreen mode
Exit fullscreen mode
Pick your answer:
A) Compile error: you cannot put a String into a List of Integer
B) It compiles, and crashes inside raw.add(...) when the String goes in
C) It prints 1, then crashes at the for loop with ClassCastException
D) It prints 1 and "not a number" and finishes happily
The answer
I compiled and ran this exact program on JDK 21 (Temurin 21.0.13).…