All 15 Arrays & Multidimensional Arrays questions
More in Arrays & Multidimensional Arrays
Advertisement
Java › Arrays & Multidimensional Arrays

How does Java implement covariant array typing, and why is this considered a design flaw that can lead to runtime ArrayStoreException?

Advanced

Answer

Java arrays are covariant, meaning Object[] arr = new String[3] is legal (a String[] reference can be assigned to an Object[] variable) since arrays retain their actual runtime component type -- but this creates a loophole where code operating on the Object[] reference can attempt to insert an incompatible type at runtime (arr[0] = Integer.valueOf(1)), which the compiler cannot catch statically and instead throws ArrayStoreException only when that specific line actually executes, illustrating why generics deliberately chose invariance instead to catch such errors at compile time.
Object[] arr = new String[3];  // legal due to covariance
arr[0] = "hello";  // fine, actual runtime type is String[]
arr[1] = Integer.valueOf(42);  // compiles fine (Object accepts Integer)... but throws ArrayStoreException at RUNTIME
Real-world example A library method accepting an Object[] parameter unknowingly receives a String[] and attempts to insert a non-String object into it, causing a production ArrayStoreException that a compile-time type system (like Java Generics' intentional invariance) would have caught much earlier during development instead.

Common follow-ups: Why did Java's generics designers choose invariance (List<String> is NOT a List<Object>) specifically to avoid this exact array pitfall?;How does the JVM implement the runtime check that throws ArrayStoreException?