Java: how to initialize String[]?
There are several ways to initialize a String
array in Java. Here are a few examples:
// method 1: using an array literal
String[] arr1 = {"apple", "banana", "cherry"};
// method 2: using the new operator
String[] arr2 = new String[] {"apple", "banana", "cherry"};
// method 3: using the new operator and specifying the size of the array
String[] arr3 = new String[3];
arr3[0] = "apple";
arr3[1] = "banana";
arr3[2] = "cherry";
// method 4: using the fill method from the Arrays class
String[] arr4 = new String[3];
Arrays.fill(arr4, "fruit");
In the first method, we use an array literal to create and initialize the array in a single step. In the second and third methods, we use the new
operator to create an empty array, and then we assign values to the array elements. In the fourth method, we use the fill
method from the Arrays
class to fill the entire array with the same value.