Initialize an Array of String in Java

In this post, we will illustrate how to declare and initialize an array of String in Java.


1. We can declare and initialize an array of String in Java by using new operator with array initializer. For example, below code snippet creates an array of String of size 5:

2. Below is an alternate syntax for declaring an array similar to C/C++ style arrays where [] appears after the variable name.

3. We can also split the code into declaration and assignment as shown below

4. We can also declare and initialize an array of String in single line without using new operator as shown below:

5. If we don’t provide any initializer, the default value of null will be assigned to each element of the array. For example,

6. We can use Arrays.fill() method to assign specified value to each element or elements between specified range of the specified array. To illustrate, consider below code

7. We can also use Arrays.setAll() method introduced with Java 8 which can be used to set all elements of the specified array, using the specified generator function. For example,

8. We can also create empty String array of size 0 as shown below:


9. We can also create an array of String using reflection. Below code will create a new array with the specified String type of length 5 with default value of null.

10. We know that length of the array is fixed and it be modified after the array is created. If we need a resizable-array implementation, we should go for an ArrayList that can grow or shrink automatically.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of