I was reading about generics and type safety and found that arrays cannot be generic in java. I also understood the covariant nature of arrays which directed me to the array store exception. I understand why this exception occurs.
I tried the below code
class SuperClass {
}
class SubClass extends SuperClass {
}
public class ArrayCheck {
public static void main (String args[]) {
SubClass arr[] = new SubClass[10];
arr[0] = new SubClass();
SuperClass[] arr1 = arr;
arr1[1] = new SuperClass();
}
}
This gives an ArrayStoreException as expected. My questions are
My question is how does JVM check for array types at runtime? Does the compiler append any additional code or is there some predefined process that JVM follows before executing instructions?
At what point this exception was raised?
I thought that the ArrayStoreException
would only occur if I try to read the array but I was wrong. So I am not understanding at what point exactly this error was raised.
Also, need a bit of clarification on the Java program execution process.
My question is how does JVM check for array types at runtime ?
When the JVM is interpreting bytecodes, the interpreter performs the relevant runtime type checks when interpreting the aastore
bytecode instruction. The relevant JVM spec link is https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.aastore.
The JIT compiler will translate the aastore
instruction into native code that does the same thing, though it may optimize away any type checks that it can determine to be redundant.
Note this kind of thing would only come to the verifier's attention if you tweaked the bytecodes to attempt to assign a reference into an array of a primitive type.
At what point this exception was raised?
When you assign a value into an array of some reference type and the value you are assigning is not assignment compatible with the base type of the array.
(Note that the exception won't be thrown for arrays of primitive types. If you try to assign a long
into an int[]
or a boolean
into an int[]
you will get a compilation error. If you try to assign an int
into a long[]
the value will be widened.)