ts_928
ts_928

Reputation: 15

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 "" ?

Upvotes: 0

Views: 90

Answers (3)

0xtvarun
0xtvarun

Reputation: 698

No you don't need to subtract one while initializing the 2D array as for the setting the values in the array to ""

Arrays.fill(array, "")

original answer here

Upvotes: 1

Saravana
Saravana

Reputation: 12817

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

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

Upvotes: 2

Pritam
Pritam

Reputation: 21

String [][] array = new String[n][n] where n is the size..so If u want to create 5*5 array..use array = new String[5][5] and index will vary from 0-4

Upvotes: 0

Related Questions