Forums Register Login

Doubt in K & B self test

+Pie Number of slices to send: Send
This from self test given in K & B book chapter 3.

code
-------------------------------------------------------
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 1
System.out.println(b[1]);
}}
-------------------------------------------------------

The answer is a class cast exception thrown at line 1. If line 1 is removed the output is 4. Can somebody explain how?
+Pie Number of slices to send: Send
Here in the code
int [] b2 = (int []) o1; // Line 1
where o1 is an 2-d array

a single Dimension array cannot accept a 2-d array

Its is given in Chap 3 with examples.

int [] [] // 2-d can accept a 2-d or a 1-d array
int [] // can accept a primitive or 1-d array
+Pie Number of slices to send: Send
Thanks for your reply...

But, could you pls explain how the output is 4 when line 1 is removed?
+Pie Number of slices to send: Send
 

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.
I AM MIGHTY! Especially when I hold this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 755 times.
Similar Threads
Array- can't understand the code.
SCJP array problem
Conversion.....
Object points to double array, yet when casting it to single array, it causes Runtime error
array
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:59:07.