Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Sub: Arrays

Ritu Kapoor
Ranch Hand
Posts: 102
Hi,

Please tell me why am I getting the following output.

Code:
-------------------------------------------------------------------
public class Casting14 {
public static void main(String[] args) {

int[][] a = {{1,2},{0,1,2},{-1,0,2}}; // 1
Object[] obj = (Object[])a.clone(); // 2

for(int i = 0; i < obj.length; i++) { // 3
int[] ia = (int[])obj[i]; // 4
System.out.print(ia[i]); // 5
}
}
}
------------------------------------------------------------
Output is 112.

Doubt 1: A multidimensional array of a specific type can be assigned to an
array object reference of same type.
Like:
int i[][]={{1,2},{2,3}};
int j[][]=i;

We can do things like that but not
int i[][]={{1,2},{2,3}};
int j[]=i;

Then how are we assigning a multidimensional array to a single dimensional array at step //2.

Doubt 2:
What is the reason why am I getting the output 112?

Thanks & Regards,
Ritu

Sandeep Chhabra
Ranch Hand
Posts: 340
Hi Ritu,

You are getting an output or 112 because of this code

As you know 2D arrays in java are just Arrays containing other arrays as elements.

here in
int[] ia = (int[])obj[i];
ia would contain an array of elements {1,2} ie. the first array in the first iteration, array of elements {0,1,2} in second iteration and array of {-1,0,2} in thrid iteration.

when you print elemnts using
System.out.print(ia[i]); // 5
so in the first iteration ia contains {1,2} and you print the i'th element of ia that is 0th element which prints 1
In the second iteration ia contains {0,1,2} and you print the i'th element of ia that is 1st element which prints 1
In the Third iteration ia contains {-1,0,2} and you print the i'th element of ia that is 2nd element which prints 2

hence the output 112;
here you are not assigning a multidimensional array to ia, infact you are assigning a single dim. array ie. array contained by the multidimensional array obj as its elements.
Note: obj is a multidim array not the arrays contained by obj.

Hope this make you clear.

Sandy
[ September 13, 2005: Message edited by: Sandeep Chhabra ]