This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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, intArray and intArray would not have individual length attributes. Next, we create a one-dimensional int array, int2, and assign it to intArray. Calling printArray() now shows that intArray has been replaced by the new int2 array. Only another reference to an array object, like intArray, 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 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! Regards, Jeff
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...)