File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Sub: Arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Sub: Arrays" Watch "Sub: Arrays" New topic

Sub: Arrays

Ritu Kapoor
Ranch Hand

Joined: Oct 03, 2004
Posts: 102

Please tell me why am I getting the following output.

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.
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,
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
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.

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

Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
wood burning stoves
subject: Sub: Arrays