String array initialization

Is there a way to clear a string array on initialization?

If i do

String foo = new String[100];

All 100 elements are set to “null” - is there a way to rewrite that initialization to make it all “” ?

Arrays are initialized with the default value of their type (null for String). Write a loop to change the value, or you can initialize the array with values like this: (but you don’t want to do this for 100 values I suppose)

String foo = {“”, “”, “”, “”};

or you can use the Arrays class

http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#fill(java.lang.Object[],%20java.lang.Object)


String [] s = new String[100];
java.util.Arrays.fill(s,"");

Thank you, I guess there’s no way to initialize it with a default value in a bulk fashion huh, explains why I couldn’t find it on google either.

You’ve already been given two ways to do it, using the Arrays class or a basic for loop:


String[] strArr = new String[100];
for(String str : strArr) str = new String("");

Cheers,
D.

To me, I wouldn’t initialize to “” if I have to loop through entire array to set that. I don’t know what your business logic is but I rather do

if (strArr[i] == null)
System.out.println(“empty”)
else
System.out.println(strArr[i])

This is my guess but they are trying to help you optimize the memory usage. So by doing String[100], it creates 100 reference to a String Class. Not an instance of String Class. So, in case you only use 50 then other half will not be loaded into memory. Anyways, if possible I’d avoid this.

This is my guess but they are trying to help you optimize the memory usage. So by doing String[100], it creates 100 reference to a String Class. Not an instance of String Class. So, in case you only use 50 then other half will not be loaded into memory. Anyways, if possible I’d avoid this.

Good point, typically I don’t use arrays anyway, better to use an ArrayList.