Initialize String[] in Java

April 10, 2018
To initialize String[] you can do:
More details are given below.

Declaration vs Initialization

Let’s consider the array strings:
The above line of code is just a declaration of an array. There is no memory allocated for the elements of strings. If you would try to assign some value to the first element of the array, eg. by executing the code:
You would get an error like “Error:(6,9) java: variable strings might not have been initialized”.
We need to initialize it then. You can do that like this:
The new operator allocated memory for the array and now we can use without problems. You can combine declaration and initialization in one statement:
You can also declare, initialize and add elements to an array in one statement:
which is equivalent to

Click here to add a comment

Leave a comment: