Originally posted by ram shah:
...The answer is a class cast exception thrown at line 1. If line 1 is removed the output is 4. Can somebody explain how?
First, consider what happens if that line is removed. The variable 'a' references a "two-dimensional" array. In
Java, a multi-dimensional array is really just an array of arrays. So 'a' references
an array where the first element a[0] references an array containing {1, 2}, and the second element a[1] references an array containing {3, 4}. In the above code, a[1] is assigned to 'b' (and note the explicit cast in that line is
not necessary). Now do you see why the output is 4?
Now consider what happens when line 1 is present. The variable 'o1' is assigned a reference to 'a', which -- as we saw above -- actually references an array
of arrays. But in line 1, we try to cast that reference to an array
of ints. Do you see what the ClassCastException occurrs?
PS: Please use
Code Tags when posting code.