Explain Codes LogoExplain Codes Logo

Checking if a string is empty or null in Java

java
prompt-engineering
best-practices
performance
Nikita BarsukovbyNikita Barsukov·Nov 23, 2024
TLDR

Check for both empty and null in String:

if (myString == null || myString.isEmpty()) { // Handle empty or null string... or string of broken dreams, Shakespeare would be disappointed }

Now, to battle the white space monsters:

if (myString != null && myString.trim().isEmpty()) { // Handle nasty whitespace-only string... like vanishing ink on a love letter }

You may have a string where every character counts:

if (myString == null || myString.length() == 0) { // Handle null or empty string... oh look, it's as empty as my coffee cup. }

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:

if (StringUtils.isEmpty(myString)) { // Handle null or empty string... it's as barren as the moon } if (StringUtils.isBlank(myString)) { // Handle null, empty, or whitespace-only strings... like feathers on a bald eagle }

The Guava guy

Guava's handy method puts the issue to rest in one go:

if (Strings.isNullOrEmpty(myString)) { // Handle null or empty string... and let's move on to conquer bugs elsewhere }

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:

// Incorrect usage, prone to error... and embarrassment if (myString.equals(null) || myString.equals("")) { // This is not the Jedi way to do the check }

Clear like a boolean

A boolean variable like isStringEmpty can clear the fog of war:

boolean isStringEmpty = myString == null || myString.trim().isEmpty(); if (isStringEmpty) { // We can see through the mirage now, the string really is empty }

Clear as a picture

A picture speaks a thousand words, or in this case, a bunch of characters in a String:

String str = /* Assign your string here */;

Think of str like a box:

📦 = str; 1. 📦 unchecked: [ ] 2. 📦 is null: [❓] 3. 📦 is empty: [✨] 4. 📦 has content: [📝]

Eyes on the box:

if (str == null || str.isEmpty()) { // 📦 is either a question or empty, like my prank gift return true; } else { // 📦 has content, surprise! like actual gift return false; }

Interpreting the scene:

  • 📦 illustrates our string str.
  • We got four stages for our 📦:
    1. Unchecked: We haven't peeked inside yet.
    2. Null: It's a big question mark ❓.
    3. Empty: There's nothing but air and it sparkles✨.
    4. Has content: Surprise! There's something inside 📝.
  • The check is quite straightforward:
    • If the 📦 is a ❓ or ✨, the string is null or empty.
    • If the 📦 contains 📝, we have a string with content.

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:

if (myString == null || myString.length() == 0) { // Handle null or empty string... like gentle whisper, every space counts }

Performance mania

Manual iteration over characters keeps you from indulging in extra instances, saving you some space fragments:

boolean isBlank(String str) { if (str == null) return true; int length = str.length(); for(int i = 0; i < length; i++) { if (!Character.isWhitespace(str.charAt(i))) { return false; // Found a real proton (i.e., a useful character) here! } } return true; // We've been invaded by those pesky white space aliens! }

HTML: Secret codes

Oh, the world of web! Spaces can hide as encoded characters (like "&nbsp;"). So, be a decoder whiz:

// After HTML parsing and decoding entities if (parsedHtmlContent == null || parsedHtmlContent.trim().isEmpty()) { // Handle null or empty decoded string... like finding a nerd in a rock concert }