Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# MultiDimensional Arrays

Lucky J Verma
Ranch Hand
Posts: 278
I read in some Java material,
MultiDimensional arrays in Java are implemented as array of arrays ie each row is a separate array.

When we define as array say , 2 x 3 array
int arr[][]={{1,2,3},
{3,4,5}};

i read ,multiple objects are created ,its not one object.
so according to my understanding , 2+1=3 objects shud be created,2for each row, 1 for storing index to 2 rows.

some other way to count objects is given.
i want to know what is true.
thnx

marc weber
Sheriff
Posts: 11343
Note: This post is in response to another response that has since been deleted (so it might seem a little out of context).

There are 3 array objects...

(2*3 = 6 gives the total number of elements -- which, in this case, are primitive ints.)
[ April 12, 2007: Message edited by: marc weber ]

marc weber
Sheriff
Posts: 11343
Originally posted by Lucky J Verma:

some other way to count objects is given...

That webpage has an error. The explanation seems correct, but the total is wrong. Where it says...
int[][] a2 = new int[10][5]; ...

This actually allocates 6 objects: a one-dimensional array of 5 elements for each of the rows, and a one-dimensional array of ten elements, with each element pointing to the appropriate row array.

...it should say something like...
This actually allocates 11 objects: a one-dimensional array of 5 elements (the ints) for each of the ten rows (so that's ten one-dimensional arrays, each containing 5 ints); and a one-dimensional array of ten elements, with each element pointing to the appropriate row array.

This can be demonstrated with the following code. It creates an int[10][5], then iterates through to print each element. The ints print as default zeros. The array objects print as [I@xxxxxx, where "[I" indicates an int array, and "xxxxxx" represents the memory address. You will see from the output that there are 11 array objects.