Other possible methods

In a different context, there may be some other methods used to create and initialize an array. It is also a matter of the style you prefer. Here are examples of the variety of array creation and initialization methods you can choose from:

String[] arr2 = new String[3];
Arrays.fill(arr2, "s");
System.out.println(Arrays.toString(arr2)); //prints: [s, s, s]

String[] arr3 = new String[5];
Arrays.fill(arr3, 2, 3, "s");
System.out.println(Arrays.toString(arr3));
//prints: [null, null, s, null, null]
String[] arr4 = {"s0", "s1", };
String[] arr4Copy = Arrays.copyOf(arr4, 5);
System.out.println(Arrays.toString(arr4Copy));
//prints: [s0, s1, null, null, null]
String[] arr5 = {"s0", "s1", "s2", "s3", "s4" };
String[] arr5Copy = Arrays.copyOfRange(arr5, 1, 3);
System.out.println(Arrays.toString(arr5Copy)); //prints: [s1, s2]

Integer[] arr6 = {0, 1, 2, 3, 4 };
Object[] arr6Copy = Arrays.copyOfRange(arr6,1, 3, Object[].class);
System.out.println(Arrays.toString(arr6Copy)); //prints: [1, 2]

String[] arr7 = Stream.of("s0", "s1", "s2").toArray(String[]::new);
System.out.println(Arrays.toString(arr7)); //prints: [s0, s1, s2]

Out of six examples above, five used the class java.util.Arrays (see the next section) to fill or copy an array. And all of them used the method Arrays.toString() to print elements of the resulting array.

The first example assigns to all the elements of an array arr2 values s.

The second example assigns the value s only to the elements from index 2 to index 3. Notice that the second index is not inclusive. That's why only one element of an array arr3 is assigned the value.

The third example copies the arr4 array and makes the new array longer in size. That is why the rest of the new array elements are initialized to the default value of String, which is null. Notice that we have put a trailing comma in the arr4 array initializer to demonstrate that it is allowed and ignored. It does not look like a very important feature. We have pointed it out just in case you see it in other people's code and wonder how it works.

The fourth example creates a copy of an array using its elements from index 1 to 3. Again, the second index is not included, so only two elements are copied.

The fifth example not only creates a copy of the range of the elements but also converts them to the Object type, which is possible because the source array is of reference type.

And the last example is using the Stream class, which we are going to discuss in Chapter 18, Streams and Pipelines.