Write a Java Program to Check if a String is Empty or Null

In Java, it’s essential to know how to check if a string is empty or null.

When working with strings, it’s common to encounter scenarios where you need to check whether a string is empty or null.

In this tutorial, we’ll discuss how to do just that in Java.


Let’s start by defining what we mean by empty and null strings.

An empty string is a string that contains no characters.

A null string is a reference to an object that doesn’t exist.

In Java, when a string is null, it means that the string variable doesn’t point to any memory location.

Now, let’s look at the code to check if a string is empty or null:

public class StringCheck {

    public static void main(String[] args) {

        String str1 = ""; // empty string
        String str2 = null; // null string

        if (str1 == null || str1.isEmpty()) {
            System.out.println("String is empty or null");
        }

        if (str2 == null || str2.isEmpty()) {
            System.out.println("String is empty or null");
        }
    }
}

In the above code, we declare two string variables, str1 and str2. str1 is an empty string, and str2 is a null string.

We use the isEmpty() method to check if the string is empty or not.

If the string is empty, the isEmpty() method returns true.

If the string is not empty, the isEmpty() method returns false.

We use the == operator to check if the string is null.

If the string is null, the == operator returns true.

If the string is not null, the == operator returns false.

We combine the isEmpty() and == operators using the || (OR) operator.

If either of the conditions is true, we print the message “String is empty or null.”

It’s worth noting that you should always check for null before checking for an empty string.

If you try to call the isEmpty() method on a null string, you will get a NullPointerException.


In conclusion, checking whether a string is empty or null is a crucial task when working with strings in Java.

You can use the isEmpty() method and the == operator to perform the check.

Remember to check for null first to avoid NullPointerExceptions.