How to Check If a String Is Empty in Java

In your day-to-day programming activities, you must be coming across multiple situations where you need to check if a string is empty. There are various ways to do this.

1. Using if-else statements and functions to check if a string is empty or null.

public class Null {

    public static void main(String[] args) {
        String str1 = null;
        String str2 = "";

        if(isNullOrEmpty(str1))
            System.out.println("First string is null or empty.");
        else
            System.out.println("First string is not null or empty.");

        if(isNullOrEmpty(str2))
            System.out.println("Second string is null or empty.");
        else
            System.out.println("Second string is not null or empty.");
    }

    public static boolean isNullOrEmpty(String str) {
        if(str != null && !str.isEmpty())
            return false;
        return true;
    }
}

Output:

str1 is null or empty.
str2 is null or empty.

2. Another useful way to check if the string is empty or not is to use the length() method.

public boolean isEmpty(String str)
    {
        return str.equals("");        //NEVER do this
    }

public boolean isEmpty(String str)
    {
        return str.length()==0;        //Correct way to check empty
    }

This method simply returns the count of characters inside the char array which constitutes the string. If the count or length is 0; you can safely conclude that string is empty.

3. Here's also an effective way to check if a String with spaces is empty or null.

public class Null {

    public static void main(String[] args) {
        String str1 = null;
        String str2 = "   ";

        if(isNullOrEmpty(str1))
            System.out.println("str1 is null or empty.");
        else
            System.out.println("str1 is not null or empty.");

        if(isNullOrEmpty(str2))
            System.out.println("str2 is null or empty.");
        else
            System.out.println("str2 is not null or empty.");
    }

    public static boolean isNullOrEmpty(String str) {
        if(str != null && !str.trim().isEmpty())
            return false;
        return true;
    }
}

Output:

str1 is null or empty.
str2 is null or empty.

Here in the isNullorEmpty(), we've added an extra method trim() which removes all leading and trailing whitespace characters in the given string. So, now if a string contains spaces only, the function returns true.



Leave a reply



Submit