Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Array Definition Question

Rod Nichols
Greenhorn
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 ?
Rod
------------------

tim hunt
Greenhorn
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
Posts: 7466
50
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).]

Nathan Pruett
Bartender
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

Rod Nichols
Greenhorn
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