javamultidimensional-array

Initialising a multidimensional array in Java


What is the correct way to declare a multidimensional array and assign values to it?

This is what I have:

int x = 5;
int y = 5;

String[][] myStringArray = new String [x][y];

myStringArray[0][x] = "a string";
myStringArray[0][y] = "another string";

Solution

  • Try replacing the appropriate lines with:

    myStringArray[0][x-1] = "a string";
    myStringArray[0][y-1] = "another string";
    

    Your code is incorrect because the sub-arrays have a length of y, and indexing starts at 0. So setting to myStringArray[0][y] or myStringArray[0][x] will fail because the indices x and y are out of bounds.

    String[][] myStringArray = new String [x][y]; is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.