This week's book giveaway is in the JDBC forum.
We're giving away four copies of Make it so: Java DB Connections & Transactions and have Marcho Behler on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Proving 2-d array stores references Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Proving 2-d array stores references" Watch "Proving 2-d array stores references" New topic

Proving 2-d array stores references

Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
I've seen (and experienced in my youth, which was only a few weeks ago I think) some confusion about the true nature of two-dimensional arrays in Java. I hope this explanation by example helps clear some of the fog for newbies.
A two dimensional array consists of a one dimensional array of references to one-dimensional arrays. The following code uses standard Java reference equality tests and reference reassignment to prove this.
First, we create a two-dimensional array of primitive int values. The program then prints the length, and calls a method for printing the array contents. If the two-dimensional array, intArray, were on object containing all elements listed in the initialization, the program would print "intArray has 12 elements". But, it prints "intArray has 3 elements", which corresponds to the number of inner braces in the initialization.
Calling printArray(), we see each array, its length, and its contents. If intArray were one object, it's elements intArray[0], intArray[1] and intArray[2] would not have individual length attributes.
Next, we create a one-dimensional int array, int2, and assign it to intArray[2]. Calling printArray() now shows that intArray[2] has been replaced by the new int2 array. Only another reference to an array object, like intArray[2], would have been validly assigned to the array referenced by int2.
For our final proof, we have the reference equality test, which proves that intArray[2] and int2 point to the same object because their references are equal.

I hope this helps clarify how multidimensional arrays work. If I put anybody to sleep with this, though, then maybe I'll just bottle it as a cure for insomnia!

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Jason Menard

Joined: Nov 09, 2000
Posts: 6450
This recent thread is somewhat relevant.
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
Thanks, Jason.
It is sorta covered in the JavaRanch Style Guide.
subject: Proving 2-d array stores references
It's not a secret anymore!