jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes 3D array question? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "3D array question?" Watch "3D array question?" New topic
Author

3D array question?

sharma ishu
Ranch Hand

Joined: Sep 10, 2012
Posts: 70
class C2{
public static void main(String[] args){
int x[][][]=new int[2][4][4];

int y[][]=new int[][]{{1,2},{3,4},{6,7}};
int z[][]=new int[][]{{8,9},{10,11},{14,15}};
x[0]=y;
x[1]=z;
System.out.println(x.length);
System.out.println(y.length);

System.out.println(x[1][1][3]);
}
}
why this code throws ArrayOutOfBound exception?
Enkita mody
Ranch Hand

Joined: Aug 06, 2012
Posts: 333

If you do compile, you would get that.


OCA7
sharma ishu
Ranch Hand

Joined: Sep 10, 2012
Posts: 70
ankita modi. wrote:If you do compile, you would get that.

Actually I want to ask why this code throws ArrayOutOfBound exception.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Fine. let me explain the scenario,
-->
I would not say the word 3D in java, the reason what i can think is that unlike c,
java array can have different shape than just traditional rectangular or square .
i.e, you can declare as in int x[][][]=new int[2][4][]; or even int x[][][]=new int[2][][];
-->
secondly, I personally feel reasoning about array of arrays is easier than 2D .. 3D etc

Coming to your question, you are trying to access the index x[1][1][3] which is not there in your array.

change your array z to int z[][]=new int[][]{{8,9},{10,11, 200, 300},{14,15}}; and now try?

hope you get the point. still if you get any doubts, feel free to post your question here...



Enkita mody
Ranch Hand

Joined: Aug 06, 2012
Posts: 333

ishusharma sharma wrote:
ankita modi. wrote:If you do compile, you would get that.

Actually I want to ask why this code throws ArrayOutOfBound exception.

Because there is no third element after {10,11}, which your code is trying to access.
 
 
subject: 3D array question?