What is the correct way to check if a String is empty or null in Java, and how can I avoid potential errors?

I’m parsing HTML data, and sometimes the string might be either null or an empty string. Here’s the condition I wrote to handle it:

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

However, this doesn’t always work correctly—especially when I remove string.equals(""). I also heard that using equals("") might not be the right approach.

So, how can I java check if string is empty or null in a safe and reliable way?

I’ve been in that spot before! The issue is that using equals(null) throws a NullPointerException, so you definitely want to avoid that. To safely java check if string is empty, I recommend this classic approach:

if (string == null || string.isEmpty()) {
    Log.d("iftrue", "String is null or empty");
} else {
    Log.d("iffalse", "String is not empty");
}

This first checks if the string is null to avoid any null pointer exceptions, and only if it’s not null does it check if it’s empty. It’s simple, safe, and pretty much the standard way to go about it in Java.

Yes, totally agree with you, Charity! But since you mentioned Android, I’d also recommend a much cleaner alternative using TextUtils.isEmpty(). It handles both the null check and the emptiness check under the hood, making it super concise and Android-friendly. It’s like a little shortcut that keeps the code neat:

if (TextUtils.isEmpty(string)) {
    Log.d("iftrue", "String is null or empty");
} else {
    Log.d("iffalse", "String is not empty");
}

This is perfect when working with Android, as it’s built to handle exactly this situation. Plus, it keeps your code nice and readable. If you’re building Android apps, this is a great go-to approach for any java check if string is empty scenario.

Definitely love what you both said! One thing I’ve learned when dealing with messy data (like HTML or form inputs) is that sometimes a string might contain spaces or tabs that you don’t see but still consider it non-empty. That’s when trim() comes in handy.

if (string == null || string.trim().isEmpty()) {
    Log.d("iftrue", "String is null, empty, or just whitespace");
} else {
    Log.d("iffalse", "String has visible characters");
}

Here, .trim() removes leading and trailing whitespace, so it ensures you’re only checking for visible content. This is especially useful when parsing HTML or messy input data, which often contains invisible characters. So, if you need to java check if string is empty or just full of whitespace, this method adds a nice layer of reliability.