Java Basic Examples Java String Handling

Java String array initialize example

Java String array initialize example shows how to initialize string array in Java. Example also shows how to declare 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, 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 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 string array using new keyword along with the size of an array as given below.

Above statement will declare and initialize 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 index as well. For example, to print 2nd element of an array you can use strDays[1]. Remember, array index starts from 0, so the first element of an array is at index 0 not 1.

Default value of the string array elements is null. So, if you initialize String array but do not assign any value to its elements, they will have null as default value. For example, 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 list of elements

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

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

Output

3) Initialize string array using 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 array both at once (as given above). If you declare an array and try to initialize it later on using above syntax, compiler will give an error “Array constants can only be used in initializers”.

See also: How to print Java array?

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

 

Join 1000+ fellow learners! Enter your email address below: