Checking if a string is empty or null in Java
Check for both empty and null in String
:
Now, to battle the white space monsters:
You may have a string where every character counts:
Robust alternatives and tricky cases
Empty strings are like UFO sightings, you've got to make sure it's legit:
StringUtils to the rescue
Apache Commons Lang bestows upon us StringUtils.isEmpty(str)
and StringUtils.isBlank(str)
, these valiant methods defend against both null and whitespace:
The Guava guy
Guava's handy method puts the issue to rest in one go:
Beware of red herrings
Never ever engage in using String.equals("")
to verify emptiness or String.equals(null)
to confirm nullness, as it's equivalent to dancing on thin ice:
Clear like a boolean
A boolean variable like isStringEmpty
can clear the fog of war:
Clear as a picture
A picture speaks a thousand words, or in this case, a bunch of characters in a String
:
Think of str like a box:
Eyes on the box:
Interpreting the scene:
- 📦 illustrates our string
str
. - We got four stages for our 📦:
- Unchecked: We haven't peeked inside yet.
- Null: It's a big question mark ❓.
- Empty: There's nothing but air and it sparkles✨.
- Has content: Surprise! There's something inside 📝.
- The check is quite straightforward:
- If the 📦 is a ❓ or ✨, the string is
null
orempty
. - If the 📦 contains 📝, we have a string with content.
- If the 📦 is a ❓ or ✨, the string is
Scenarios nuanced
Leading or trailing space invaders
Spaces at the start or end of strings can matter, in such cases, trim()
may feel too aggressive:
Performance mania
Manual iteration over characters keeps you from indulging in extra instances, saving you some space fragments:
HTML: Secret codes
Oh, the world of web! Spaces can hide as encoded characters (like " "
). So, be a decoder whiz:
Was this article helpful?