ArrayStoreException in Java Array Assignment
Given these classes: and this the code fragment: What is the result? -
- 
Community Votes
100% of anonymous learners picked answer A. Votes are pick records left by other test-takers — they are not the verified answer.
Community Insight
The code compiles due to covariant array types but fails at runtime because the array's component type is B, not A or C.
This question tests understanding of Java array covariance and runtime type safety, demonstrating that assigning an incompatible object to a covariant array throws an exception.
Many learners choose D (fails to compile) because they confuse compile-time polymorphism with runtime array storage constraints.
Community Discussion (3 comments)
Comments & Corrections
No comments yet — spotted an error or have a note? Share it below.
Expert Analysis
Why the Answer Is Correct
The variablevalues is declared as type A[], which allows it to reference arrays of any subtype of A. However, it is instantiated as new B[2], meaning the actual runtime object is an array of type B[]. When values[0] = new C is executed, the JVM checks if C is assignable to B. Since C is not a subclass of B, the JVM throws an ArrayStoreException at runtime.Why the Other Options Are Wrong
Option B and C are incorrect because the program does not print anything; it crashes before reaching any print statements. Option D is incorrect because the code compiles successfully. The assignmentnew C to an A[] reference is valid at compile time due to inheritance, even though it is invalid for the specific runtime array type B[].Community Comment Notes
Community members correctly identify thatArrayStoreException is thrown because the array was created as B[]. One user noted that while A[] can hold B objects, it cannot hold C objects if the underlying array is specifically typed as B[]. Another comment clarified that if the array were created as new A[2], the assignment would have succeeded. Exam Strategy
Remember that Java arrays are covariant: an array of subtypes can be assigned to a reference of a supertype. However, the runtime check ensures that only elements compatible with the actual array's component type can be stored.
Frequently Asked Questions
Why doesn't the compiler catch this error?
The compiler only knows values is A[]. Since C extends A, the assignment is legal at compile time. Runtime checks enforce the actual array type.
How to fix the code to avoid the exception?
Change the instantiation to new A[2] so the array can hold any subtype of A, including both B and C.