Java Initialize String array [closed]

No, because you need to tell the compiler how big you want the array to be. Remember that arrays have a fixed size after creation. So any of these are okay, to create an empty array:

String[] array = {};
String[] array = new String[0];
String[] array = new String[] {};

Admittedly an empty array is rarely useful. In many cases you’d be better off using an ArrayList<String> instead. Of course sometimes you have to use an array – in order to return a value from a method, for example.

If you want to create an array of a specific length and then initialize it later, you can specify the length:

String[] array = new String[5];
for (int i = 0; i < 5; i++) {
    array[i] = String.valueOf(i); // Or whatever
}

One nice feature of empty arrays is that they’re immutable – you can’t change the length, and because then length is 0 there are no elements to mutate. So if you are going to regularly use an empty array of a particular type, you can just create it once:

private static final String[] EMPTY_STRING_ARRAY = {};

… and reuse that everywhere.

Leave a Comment