Originally posted by Jarlax King:
I am trying to get a grasp on multi-dimensional arrays and am having a bit of trouble. Here is a question from the book that I would like some help understanding. The correct answer is a,b,e,f but I am not really getting why. Can anyone help me out?
1. public class Test {
2. public static void main (String [] args) {
3. byte [][] big = new byte [7][7];
4. byte [][] b = new byte [2][1];
5. byte b3 = 5;
6. byte b2 [][][][] = new byte [2][3][1][2];
7.
8. }
9. }
Which of the following lines of code could be inserted at line 7 and still allow the code to compile? (choose 4 that would work)
A. b2[0][1] = b;
B. b[0][0] = b3;
C. b2[1][1][0] = b[0][0];
D. b2[1][2][0] = b;
E. b2[0][1][0][0]=b[0][0];
F. b2[0][1]=big;
You can look at multidimensional arrays as being an array of arrays. The left and right side of the assignment operator should be compatible.
Considering the answer choices,
-b2 is a four dimensional array. It needs 4 indices to effectively point to an element of type byte. Giving only 2 indices, points to a 2 Dimensional sub-array. b2[0][1] refers to a 2D array (same as b which is also a 2D array), which is why answer A is right.
-b[0][0] refers to a byte element, which is choice B
-b2[1][1][0] refers to a 1D array but b[0][0] on the RHS is a single byte element.This raises a compiler error.
- b2[1][2][0] again refers to a 1D array but b (on the RHS) is a 2D array. Causes a compiler error.
b2[0][1][0][0] points to a single byte element and is compatible with the RHS b[0][0], which also refers to a single byte element.
-b2[0][1] refers to a 2D array and is compatible with big, also a 2D array.
[ May 12, 2004: Message edited by: V Bose ]