Java – Initialize String Array
To initialize String Array in Java, define a string array and assign a set of elements to the array, or define a string array with specific size and assign values to the array using index.
Initialize String Array with Set of Strings
Declare a variable of type String[] and assign set of strings to it using assignment operator.
In the following program, we will initialize a string array fruits
with four string elements.
Java Program
public class Example { public static void main(String[] args){ String fruits[] = {"apple", "banana", "mango", "orange"}; for(String fruit: fruits) { System.out.println(fruit); } } }
Output
apple banana mango orange
Initialize String Array – Second Method
As already mentioned in the introduction, we can initialize a string array by defining a string array with specific size, and then assigning values to its elements using index.
In the following program, we will define a string array fruits
of size four and assign values to the elements using index.
Java Program
public class Example { public static void main(String[] args){ String fruits[] = new String[4]; fruits[0] = "apple"; fruits[1] = "banana"; fruits[2] = "mango"; fruits[3] = "orange"; for(String fruit: fruits) { System.out.println(fruit); } } }
Output
apple banana mango orange
Conclusion
In this Java Tutorial, we learned different ways to initialize String Array in Java, with the help of example programs.