class Dims {
public static void main(String[] args) {
int[][] a = {{1,2,}, {3,4}};
int[] b = (int[]) a[1];
Object o1 = a;
int[][] a2 = (int[][]) o1;
int[] b2 = (int[]) o1; // Line 7
System.out.println(b[1]);
}
}
I have a doubt in the above piece of code in Java.
Why does it give a Runtime Exception and not a compile time error at line number 7?
Because o1 is an int[][], not an int[]. The RuntimeException you get is a ClassCastException, because the first is an array of int arrays, and the latter just an array of ints.
You don’t get a compile time error, because o1 is defined as an Object. So at compile time, it could hold anything that is derived from object, which is in fact every Type in Java except the primitive types long, int, short, byte, char, double, float and boolean. So, at compile time it seems possible that the object might in fact be an int[].