This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Multidimensional Array Assignments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Multidimensional Array Assignments" Watch "Multidimensional Array Assignments" New topic

Multidimensional Array Assignments

Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
Experimenting with the following code:
byte[][] b1 = new byte[4][4];
byte[][] b2 = new byte[2][2];
byte[][][][] b3 = new byte[5][6][7][8];
A. b1[1][0] = b2; //found: byte[][] required: byte
B. b3[1] = b2; //found: byte[][] required: byte[][][]
C. b3[1][1] = b2; //OK
D. b3[1][1][1] = b2; //found: byte[][] required: byte[]
I think I understand A and C, but can someone explain B and D.

SCJP 1.4, SCWCD 1.3, SCBCD 1.3
Santhosh Kumar
Ranch Hand

Joined: Nov 07, 2000
Posts: 242
Hi Roger,
1. Basically there is no multidimensional array concept in java.
2. Array are themselves objects and can hold reference to other objects.
From point 2, you can create array which holds object reference to other array, simulating the multidimensional array.
To answer your question,
B: b3 is array of (array of (array of (array of (bytes))))
b3[1] is array of (array of (array of (bytes))) but where b2 is array of (array of (bytes)). So you cannot assign it.
D: b3[1][1][1] is array of (bytes). So you cannot assign b2 which is array of ((array of (bytes))
Hope this helps.
[ April 18, 2003: Message edited by: Santhosh Kumar ]
Nico Schlebusch

Joined: Jan 22, 2003
Posts: 5
When you assign a value to an one-dimensional array you assign a specific value (primitive / reference) to a position in the array. E.g.

When you have a two-dimensional array you must assign a specific value to each position in the array or you can assign a one-dimensional array to a position in the array. E.g.


As you can see in the last piece of code, the dimension of the array on the right-hand side of the = is one dimension less than the dimension of the array to the left of the =.
Thus, for your var b3 (a 4 dimensional array) in B you must assign a 3 dimensional array to a specific position:

For D, you need a one-dimensional array:

Hope this helps.

Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
Got it! And I now also understand why this is wrong:
b3[1][1][1][1] = b2;
And why this is right:
b3[1][1][1][1] = 1;
I agree. Here's the link:
subject: Multidimensional Array Assignments
Similar Threads
Once more about Array
A SCJP exam question (about array variable assign)
Doubt About the output of this Question
A doubt in bitwise operator