[java] Checking if a string is empty or null in Java

I'm parsing HTML data. The String may be null or empty, when the word to parse does not match.

So, I wrote it like this:

if(string.equals(null) || string.equals("")){
    Log.d("iftrue", "seem to be true");
}else{
    Log.d("iffalse", "seem to be false");
}

When I delete String.equals(""), it does not work correctly.

I thought String.equals("") wasn't correct.

How can I best check for an empty String?

This question is related to java

The answer is


You can use Apache commons-lang

StringUtils.isEmpty(String str) - Checks if a String is empty ("") or null.

or

StringUtils.isBlank(String str) - Checks if a String is whitespace, empty ("") or null.

the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API


This way you check if the string is not null and not empty, also considering the empty spaces:

boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
    // handle the validation
}

import com.google.common.base

if(!Strings.isNullOrEmpty(String str)) {
   // Do your stuff here 
}

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.

Example:

System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true

Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).

Example:

System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

Correct way to check for null or empty or string containing only spaces is like this:

if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }