Why does Java allow arrays of size 0?

Solution 1:

It signifies that it is empty. I.e. you can loop over it as if it had items and have no result occur:

for(int k = 0; k < strings.length; k++){
   // something
}

Thereby avoiding the need to check. If the array in question were null, an exception would occur, but in this case it just does nothing, which may be appropriate.

Solution 2:

Why does Java allow arrays of size 1? Isn't it pretty useless to wrap a single value in an array? Wouldn't it be sufficient if Java only allowed arrays of size 2 or greater?

Yes, we can pass null instead of an empty array and a single object or primitive instead of a size-one-matrix.

But there are some good arguments against such an restriction. My personal top arguments:

Restriction is too complicated and not really necessary

To limit arrays to sizes [1..INTEGER.MAX_INT] we'd have to add a lot of additional boudary checks,(agree to Konrads comment) conversion logic and method overloads to our code. Excluding 0 (and maybe 1) from the allowed array sizes does not save costs, it requires additional effort and has an negative impact on performance.

Array models vector

An array is a good data model for a vector (mathematics, not the Vector class!). And of course, a vector in mathematics may be zero dimensional. Which is conceptually different from being non-existant.


Sidenote - a prominent wrapper for an (char-)array is the String class. The immutable String materializes the concept of an empty array: it is the empty String ("").