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 Array Reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array Reference" Watch "Array Reference" New topic

Array Reference

John Wolf
Ranch Hand

Joined: Feb 18, 2002
Posts: 64
Could someone please give me an example of what is being implied here,

"If you assign an array to a previously declared array reference, the array you're assigning must be the same dimension as the reference you're assigning it to." - K&B

[ May 03, 2005: Message edited by: Sumit Sadana ]

SCJP 1.2, SCJP 1.4, SCJA, SCWCD 1.4<br /> <br />------------------------------<br />
Ranch Hand

Joined: Apr 01, 2005
Posts: 431

This is very simple. Consider the following example.

int a1[];
int a2[][];
int a3[][][];

a2=new int[3][2];

now, a1 is a 1 dimensional array, a2 is a 2 dimensional array and a3 is a 3 dimensional array.

Now a1 as not defined. Can u assign a2 to a1 like a1=a2;???

No.. You cant because they are of difft dimensions. But you can assign
a1=a2[0]; because a2[0] is a 1 dimensional array of size 2.

you cannot assign a3=a2; but you can do as
a3=new int[3][][]; and a3[0]=a2;


Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
It's just another piece of fallacy that many technical books portray.
Any suggestions that refer to 2 (or more) dimensional arrays should be ignored, since multi-dimensional arrays are not supported in Java and heeding such advice will lead to further confusion on top of the already existing confusion. This is what I assume your book is erroneously attempting to communicate.

The real point is that a reference whose type is array, cannot be assigned to another reference of a different type (except for java.lang.Object, java.lang.Cloneable or with an explicit cast, but that is irrelevant). By no strange coincidence, a reference of type (for example) int[] (array of int) is not of the same type as a reference of type int[][] (array of array of int) - the distinction is obvious, is it not?

I sometimes think that this forum goes in cycles of questions, with the same question being asked at certain time intervals.
I'll say it one more time:
Java does not have support for multi-dimensional arrays
(and the argument that the JLS quotes the use of multi-dimensional arrays holds no water).

Tony Morris
Java Q&A (FAQ, Trivia)
John Wolf
Ranch Hand

Joined: Feb 18, 2002
Posts: 64
Thank you Guys! This is makes lot more sense now.

I agree. Here's the link:
subject: Array Reference
It's not a secret anymore!