Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

# Multidimensional Arrays

Ravi Ahuja
Ranch Hand
Posts: 45

[ans]
Hello Everyone
Can Anyone explain me what is the answer of the above program
and why ?
[/ans]

Barry Gaunt
Ranch Hand
Posts: 7729
Please mention the source of any mock exam question that you post.

Greg L Tonn
Ranch Hand
Posts: 52
The only one I know that would work is "B" but I don't know the others.

Could someone give an idea of how to draw/map this out on paper so we could figure it out for ourselves?

Thanks

Andy Morris
Ranch Hand
Posts: 78
The answer is A, B, E and F (correct me if you disagree!)

A: b2[0][1] refers to a 2d array, which b is.
B: b[0][0] refers to a byte value, which b3 is.
E: b2[0][1][0][0] refers to a single byte value, as does b[0][0]
F: b2[0][1] refers to a 2d array, which 'big' is.

C: b2[1][1][0] refers to a 1d array, whereas b[0][0] refers to a single byte
D: b2[1][2][0] refers to a 1d array, whereas b is a 2d array

If you can't just see the number of dimensions when looking at the code you could look at an array like this:

byte b2 [][][][] = new byte [2][3][1][2]; //a 4d array

If you put:
b2[0][1][0][0] you're referring to a single value
b2[0][1][0] you're referring to a 1d array
b2[0][1] you're referring to a 2d array
b2[0] you're referring to a 3d array
b2 you're referring to a 4d array

Notice the pattern - so you could apply this to other arrays:

e.g
byte [][] b = new byte [2][1]; //a 2d array

b[0][0] single value
b[0] 1d array
b 2d array

There might be easier ways of working this out but I think once you're familiar with working with arrays (through practise) it's like doing timestables and the answer is obvious.
[ November 27, 2006: Message edited by: Andy Morris ]

Greg L Tonn
Ranch Hand
Posts: 52
Andy,

So it doesn't matter what the size of the array is only the demensions?

Andy Morris
Ranch Hand
Posts: 78
For compilation only the dimensions matter.
For runtime the size does matter (you'll get ArrayIndexOutOfBoundsExceptions if you reference an index that is not valid).

Nikhil Bansal
Ranch Hand
Posts: 60
Thanks Andy for your inputs.It really helped.

Regards

Nikhil