[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");
    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

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 */ }

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.


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).


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

You can use Apache commons-lang

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


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