-
Initializing Arrays
I used java.util.Arrays to initialize an integer array. Please review the code below:
Code:
int[] array = new int[10];
Arrays.fill(array, 0);
for(int i=0;i<array.length;i++)
System.out.println("Value at " + i + " is " + array[i]);
Output:
Code:
Value at 0 is 0
Value at 1 is 0
Value at 2 is 0
Value at 3 is 0
Value at 4 is 0
Value at 5 is 0
Value at 6 is 0
Value at 7 is 0
Value at 8 is 0
Value at 9 is 0
Can I also initialize a String array uisng java.util.Arrays? If yes, please tell me the method.
Thanks.
-
I think what you're trying to do this:
Code:
String[] array = new String[10];
array[0] = "Zero";
array[1] = "One";
//etc
-
Thanks. But I want some function to initialize a String array without putting values manually.
Thanks.
-
Just do what Lang said inside a loop.
Code:
for(int i = 0; i < array.length; i++){
array[i] = "This is the string at index" + i;
}
-
Can I also initialize a String array uisng java.util.Arrays? If yes, please tell me the method.
Yes.
Code:
String[] s = new String[6];
Arrays.fill(s, "");
System.out.printf("s = %s%n", Arrays.toString(s));
-