ts_928 ts_928 - 12 days ago 8
Java Question

Creating 2D Array with given dimensions (Simple)

When creating a 2D array with say 5 rows and 5 columns, do you subtract one when initializing it?

String [][] array;
array = new String [4][4];


Would this create a 5 x 5 array since when you index it starts from 0?
Also is there a way to set an array to blank, so for strings it would have all spots containing "" ?

Answer

no, you should initialize array with the size you need.

To fill array with some default values, use Arrays.fill

String[][] arr = new String[5][5];
for (String[] ar : arr) {
    Arrays.fill(ar, "");
}
System.out.println(Arrays.deepToString(arr));

output

[[, , , , ], [, , , , ], [, , , , ], [, , , , ], [, , , , ]]