• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

3D array question?

 
sharma ishu
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 333
Firefox Browser Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you do compile, you would get that.
 
sharma ishu
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 333
Firefox Browser Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic