Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sub: Arrays

 
Ritu Kapoor
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?


Please clarify me on this.

Thanks & Regards,
Ritu
 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic