Java – Define String Array of Specific Size
To define String array of specific size in Java, declare a string array and assign a new String array object to it with the size specified in the square brackets.
The syntax to define String Array of specific size is
</>
Copy
String arrayName[] = new String[size];
//or
String[] arrayName = new String[size];
where arrayName
is the String array name and size
is the number of elements that we would like to store in the String array.
Example
In the following program, we will define a string array fruits
with size of four. After defining the string array, we can initialize individual elements of the array using index.
Java Program
</>
Copy
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 how to define String array in Java, with the help of example programs.