Tuesday, December 1, 2020

Example to Test Whether String is Null or Empty in Java

This is the short tutorial to test whether the given string is null or empty.

Let's look at the following example:
public class StringUtil {
    public static void main(String[] args) {
        String nonEmptyString = "non empty string";
        String nullString = null;
        String emptyString = "";
        String emptyStringWithWhiteSpace = " ";
        boolean isNonEmpty = isNullOrEmpty(nonEmptyString);
        System.out.println(isNonEmpty); //false
        boolean isNullString = isNullOrEmpty(nullString);
        System.out.println(isNullString); //true
        boolean isEmptyString = isNullOrEmpty(emptyString);
        System.out.println(isEmptyString); //true
        boolean isEmptyStringWithWhiteSpace = isNullOrEmpty(emptyStringWithWhiteSpace);
        System.out.println(isEmptyStringWithWhiteSpace); //true
    }

    private static boolean isNullOrEmpty(String str) {
        if(str == null || str.trim().isEmpty())
            return true;
        return false;
    }

}
  
Here, we are using different types of string value to test whether it is null or empty. In order to test we are simply creating the isNullOrEmpty(String str) method, which will return true if the string is null or empty and false if it is not. If the first condition is satisfied it will not test the second one because we are using OR logic. So, even if the "str" is null it will not throw an error.


The reason behind using trim() is to remove any leading or trailing white space from the given string. So that isEmpty() method will not consider the empty string with white space as a non-empty string.
Basically, isEmpty() will test the length of the string to return the boolean value. So, if the given string contains white space, even if the string is empty it will return false.
Share:

0 comments: