0

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

3
  • The rules are no different than when creating a one-dimensional array. Do you subtract 1 when creating one of these? Commented Nov 29, 2016 at 4:18
  • 1
    No. Valid indices of an array are 0 to length - 1. Your new String[4][4] would have valid indices 0, 1, 2 and 3. That is a total of 4 (per dimension). Commented Nov 29, 2016 at 4:22
  • This is a good time for you to learn to experiment and Google thoroughly before asking. While elementary questions are acceptable on Stack Overflow, unresearched ones aren't. Commented Nov 29, 2016 at 4:30

3 Answers 3

2

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

[[, , , , ], [, , , , ], [, , , , ], [, , , , ], [, , , , ]]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.