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

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?


Solution 1:

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:

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:

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