aspose file tools*
The moose likes Beginning Java and the fly likes Array Definition Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array Definition Question" Watch "Array Definition Question" New topic
Author

Array Definition Question

Rod Nichols
Greenhorn

Joined: Apr 19, 2001
Posts: 23
I am going through the book "A Programmer's Guide to Java Certification" and I came across the following code in the review questions. According to the question, the following two array definitions are valid :
int []a[] = new int [4][4];
and
int []a[] = new int [4][];
My question is this: What actually is created by each of these two statements ?
Thank You in Advance
Rod
------------------
tim hunt
Greenhorn

Joined: Apr 19, 2001
Posts: 9
Rod,
A 2 -dimensional array is created. I do fully remember what there used for. In terms of the exam I think that you just need to know that they are valid.
Hope this helps,
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4699
    
    7

The first declaration creates an array that has 4 elements. Each of those 4 elements is an array of 4 integers, all initialized to 0. This simulates a 4x4 array of integers.
The second declaration is similar: It creates an array that has 4 elements, each of which can contain an array of integers. The difference with this and the first declaration is that these four elements are all null. In order to make it a two dimensional 4x4 array of integers, you would have to do the following:
<pre>
for ( int i = 0; i < a.length; i++ )
{
a[i] = new int[4];
}
</pre>
Note that you can even make the lengths of the "second dimension" arrays different this way:
<pre>
// create a triangular 2-dimensional array
for ( int i = 0; i < a.length; i++ )
{
a[i] = new int[i+1];
}
</pre>

[This message has been edited by JUNILU LACAR (edited June 20, 2001).]


Junilu - [How to Ask Questions] [How to Answer Questions]
Nathan Pruett
Bartender

Joined: Oct 18, 2000
Posts: 4121

Junilu is correct...

I'll help out by making snazzy ASCII illustrations of the arrays produced...

int []a[] = new int[ 4 ][ 4 ] =



int []a[] = new int[4][] =


Enjoy!
-Nate


-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Rod Nichols
Greenhorn

Joined: Apr 19, 2001
Posts: 23
Tim, Junilu and Nate,
Thank you for the feedback! This does answer my question, I was more interested in the left side of the assignment statement but this clarifies it. I can conclude now that these three declarations are equivalent :
int []a[]
and
int a[][]
and
int[][] a
Thanks guys
Rod
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array Definition Question