Skip to content

Java String array initialize example

Java String array initialize example shows how to initialize string array in Java. The example also shows how to declare a string array and various ways to initialize it.

How to declare String array in Java?

You can declare an array using <type>[] array_name; syntax like given below.

By declaring an array you are telling the compiler to create a reference to the array which will be created later. Please note that declaring an array does not allocate memory in the heap.

If you try to use the reference at this point, the compiler will give an error “The local variable strDays may not have been initialized”. You need to initialize the array before you can use it.

How to initialize String array in Java?

There are several ways using which you can initialize a string array in Java. Initializing an array will allocate memory for it.

1) Initialize string array using new keyword along with the size

You can initialize a string array using the new keyword along with the size of an array as given below.

The above statement will declare and initialize an array in a single statement. It will create a string array of 7 elements. You can now add elements to the array by referring to its index as given below.

You can access elements of an array using the index as well. For example, to print the 2nd element of an array you can use strDays[1]. Remember, the array index starts from 0, so the first element of an array is at index 0, not 1. Similarly, the last element of the array is located at the array length – 1 index.

The default value of the string array elements is null. So, if you initialize the String array but do not assign any value to its elements, they will have null as the default value. For example, the below code will print null because we have not assigned any value to element 4 of an array.

2) Initialize string array using new keyword along with the list of elements

You can also initialize an array using the new keyword and specify the array elements along with it as given below.

The above statement will declare an array and initialize it with 3 elements. Note that we have not specified the size of an array, just the elements of it.

Output

3) Initialize string array using a list of elements

You can also skip mentioning new keyword and directly assign the list of elements to an array like given below.

Please note that this approach only works when you declare and initialize the array both at once (as given above). If you declare an array and try to initialize it later on using the above syntax, the compiler will give an error “Array constants can only be used in initializers”.

See also: How to print Java array?

This example is a part of the Java Array tutorial with examples.

Please let me know your views in the comments section below.

About the author

1 comments

Leave a Reply

Your email address will not be published.