Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Definition Question

 
Rod Nichols
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 7329
45
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic