Check if a string is empty or null in Java

thumbnail

In this tutorial, you will learn about the code to check if a string empty or null using if-else statement and functions in Java. Here, we will create four strings str1, str2, str3, and str4.

Str1 contains null value, str2 is an empty string, str3 contains string, and str4 contains white space. We also need to create two functions.

First, isNullOrEmpty() to check the string is null or empty. It checks it using a null check using != null and isEmpty() method of string. In short, if a string isn’t a null and isEmpty() return false, it’s either null or empty. Else, it is.

Second, isNullOrEmptyWithTrim() used extra method trim() which remove all leading and trailing whitespace characters in the given string. So, if a string only contains spaces only, the function will returns true.

Example: Check if string is Empty or Null

public class CheckStringEmptyNull {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "";
        String str3 = "abc123";
        String str4 = "   ";
        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.");
        }
        if(isNullOrEmpty(str3)){
            System.out.println("Third string is null or empty.");
        } else {
            System.out.println("Third string is not null or empty.");
        }
        if(isNullOrEmptyWithTrim(str4)){
            System.out.println("Fourth string is null or empty.");
        } else {
            System.out.println("Fourth string is not null or empty.");
        }
    }
    
    public static boolean isNullOrEmpty(String str) {
        return !(str != null && !str.isEmpty());
    }
    
    public static boolean isNullOrEmptyWithTrim(String str) {
        return !(str != null && !str.trim().isEmpty());
    }
}

The output will be:

First string is null or empty.
Second string is null or empty.
Third string is not null or empty.
Fourth string is null or empty.

To check more awesome tutorial java you can check it through this link.

Back To Top