Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Two Dimensional Arrays

 
Aruna Balasuriya
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test {

public static void main(String[] args) {

int x [] [] = new int [3][5] ;
x[0]=new int[]{1,2,3,4,5,6,7} ;

}

}

According to declaration x[0] may contain only 5 values but I fill 7 values but it wont generate array out of bound exception.why?
 
Addy Micheal
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try 5 values or 6 values.
 
Henry Wong
author
Marshal
Pie
Posts: 20995
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aruna Balasuriya wrote:
According to declaration x[0] may contain only 5 values but I fill 7 values but it wont generate array out of bound exception.why?


Keep in mind that Java doesn't really support multidimensional arrays. It supports arrays of arrays. When you instantiated the two dimensional array, the new operator instantiates an array of size three, and then instantiates int arrays of size 5, in each of the three array elements.

In the next statement, you are instantiating an int array of size seven, and replaced the first element of the int array array with it. So, X is an array of arrays, with the first element having an int array of size 7, and the other two elements having an int array of size 5.

Henry
 
Aruna Balasuriya
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aruna Balasuriya wrote:public class Test {

public static void main(String[] args) {

int x [] [] = new int [3][5] ;
x[0]=new int[]{1,2,3,4,5,6,7} ;

}

}

According to declaration x[0] may contain only 5 values but I fill 7 values but it wont generate array out of bound exception.why?


Trying with 6 vales also DIDNOT result array out of bound exception.
 
Henry Wong
author
Marshal
Pie
Posts: 20995
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aruna Balasuriya wrote:
Trying with 6 vales also DIDNOT result array out of bound exception.


For the same reason, that I explained in my previous post.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic