To initialize String[] you can do:
1 2 3 |
String[] strings = new String[2]; |
More details are given below.
Declaration vs Initialization
Let’s consider the array strings:
1 2 3 |
String[] 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:
1 2 3 4 |
String[] strings; strings[0] = "The string"; |
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:
1 2 3 4 |
String[] strings; strings = new String[2]; |
The new operator allocated memory for the array and now we can use without problems. You can combine declaration and initialization in one statement:
1 2 3 |
String[] strings = new String[2]; |
You can also declare, initialize and add elements to an array in one statement:
1 2 3 |
String[] strings = {"immediately", "elements"}; |
which is equivalent to
1 2 3 4 5 |
String[] strings = new String[2]; strings[0] = "Immediately"; strings[1] = "elements"; |