How can I initialize a String array with length 0 in Java?
This is your bare bones, no frills method to initialize an empty String array:
Minimalist, zero-length String array at your disposal - Quick, clean and far less chance of tripping up on a NullPointerException
than simply resorting to null
.
The upsides of reuse: memory efficiency and performance
In a world rushing towards sustainable living, why not apply the same principle to our code? We reuse references to our benevolent zero-length array:
Next time you need an empty array just whip out ArrayUtils.EMPTY_STRING_ARRAY
. It's like reusable shopping bags but for your code. The same static final
array being used everywhere? That's memory efficiency right there.
Other ways to get yourself an empty array
With the 'new' keyword
As with many things in life, you can get an empty array simply by explicitly asking for one:
"Now available in 0D (zero dimensions)"
The power of standing on the shoulders of giants with Apache Commons Lang
With the same principle of reusability, the open-source gods Apache offer us ArrayUtils.EMPTY_STRING_ARRAY
:
"Apache provides...and all is right with the world."
There is no result, but there is also no error. The magic of empty arrays in methods
Imagine your method is a hyper-efficient post office. It processed everything, but found nothing to return. Instead of resorting to the equivalent of an error-ridden "return to sender" (null
), you use an empty array:
See, the post office is still open, just nothing to deliver right now.
Understanding size and arrays
Sizing up your array
Unlike your phone storage, once you've chosen an array size in Java, there's no going back.
Flexing with ArrayList<>
If you like to change it up, ArrayList<String>
gives you a list that can grow or shrink on demand:
Covert ops - shifting back to an array when you want to:
The pitfalls of not initializing
If you see this, watch out!
notInitialized
is essentially cloaked. Won't point to an array until it's assigned one, and will throw NullPointerException
s for fun until then.
Java's consistency: Comfort in predictability
Consistency, the staple of programming. The syntax for initializing arrays of different types remains the same:
Was this article helpful?