What is the best way to check if a String is null or empty in Java?
I’m currently parsing HTML data, and sometimes the String can be null or empty when the expected word doesn’t match. To handle this, I wrote the following check:
if(string.equals(null) || string.equals("")){
Log.d("iftrue", "seem to be true");
}else{
Log.d("iffalse", "seem to be false");
}
However, when I remove string.equals("")
, the condition doesn’t work correctly. I was under the impression that String.equals("")
wasn’t the right approach.
How can I correctly check if a Java string is null or empty?
Hey there! I see what you’re getting at. Your current check with string.equals(null)
is problematic because it throws a NullPointerException
if the string is null
. Instead, you want to do a null check first and then check if it’s empty. Here’s how you can do it safely:
if (string == null || string.isEmpty()) {
Log.d("iftrue", "java string is null or empty");
}
This approach works perfectly! The isEmpty()
method checks whether the string is empty, so it’ll catch cases where it’s an empty string ""
. It’s clean and simple, and handles both null
and empty strings without issues.
Great point, Ian! If you’re open to using external libraries, Apache Commons has a method that simplifies this even further. The method StringUtils.isBlank()
handles null
, empty, and whitespace-only strings all in one go. Here’s how you can use it:
import org.apache.commons.lang3.StringUtils;
if (StringUtils.isBlank(string)) {
Log.d("iftrue", "java string is null or empty");
}
This is super useful when you also want to treat strings that only contain spaces as ‘empty.’ If that’s something you need, this method is a great option!
Right on, Jacqueline! But if you don’t want to add an external library, you can handle whitespace without it. Just use the trim()
method to remove leading and trailing spaces, and then check if the string is empty. Here’s how you can do it:
if (string == null || string.trim().isEmpty()) {
Log.d("iftrue", "java string is null or empty");
}
This will ensure that even strings like " "
(spaces only) are treated as empty, which wasn’t considered in your initial approach. It’s a nice way to handle the case where you might have accidental spaces that shouldn’t be counted as content.