Explicitly assigning values to a 2D Array?

The best way is probably to just declare and assign all values at once. As shown here. Java will automatically figure out what size the array is and assign the values to like this.

int contents[][] = { {1, 2} , { 4, 5} };

Alternatively if you need to declare the array first, remember that each contents[0][0] points to a single integer value not an array of two. So to get the same assignment as above you would write:

contents[0][0] = 1;
contents[0][1] = 2;
contents[1][0] = 4;
contents[1][1] = 5;

Finally I should note that 2 by 2 array is index from 0 to 1 not 0 to 2.

Hope that helps.


Are you looking to assign all values in a 2D array at declaration time? If so, it works as follows:

int[][] contents = new int[][]{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

Remember that a 2D array in Java is really an array of arrays, but Java gives you some special syntax if you do this at declaration time.


Looks like you want to assign a row in one statement?

After declaration like:

int[][] matrix = new int[2][2] //A

or

int[][] matrix = new int[2][] //B

You can use two kinds of assignment statement:

matrix[0][0]=1; //can only used in A, or will throw the NullPointerException.
matrix[1]=new int[] {3,3,5};//This can be used both in A and B. In A, the second row will have 3 elements.

Tags:

Java