Checking if a string is empty or null in Java

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

import com.google.common.base.Strings;

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

Solution 5 - Java

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2027811View Question on Stackoverflow
Solution 1 - JavaPradeep SimhaView Answer on Stackoverflow
Solution 2 - JavaMakotoView Answer on Stackoverflow
Solution 3 - JavaEvgeniy DorofeevView Answer on Stackoverflow
Solution 4 - JavahariView Answer on Stackoverflow
Solution 5 - JavaAlécio CarvalhoView Answer on Stackoverflow