Arrays in java are fixed in length. Why does Java allow arrays of size 0 then?
String[] strings = new String[0];
Consider this (a more detailed explanation of Noon's answer):
public String[] getStrings() {
if( foo ) {
return null;
} else {
return new String[] {"bar, "baz"};
}
}
String[] strings = getStrings();
if (strings != null) {
for (String s : strings) {
blah(s);
}
}
Now compare it to this:
public String[] getStrings() {
if( foo ) {
return new String[0];
} else {
return new String[] {"bar, "baz"};
}
}
// the if block is not necessary anymore
String[] strings = getStrings();
for (String s : strings) {
blah(s);
}
This (returning empty arrays rather than null values), is in fact a best practice in Java API design world.
Besides, in Java, you can covert Lists (e.g. ArrayList) to arrays and it only makes sense to convert an empty list to an empty array.