How to check if a string is blank (empty, null, or contains only whitespace) in Java

1 Answer

0 votes
public class IsBlankOrEmpty {

    public static boolean isBlankOrEmpty(String str) {
        // Check for null or empty string
        if (str == null || str.isEmpty()) {
            return true;
        }

        // Check if the string contains only whitespace
        for (char ch : str.toCharArray()) {
            if (!Character.isWhitespace(ch)) {
                return false; // Found a non-whitespace character
            }
        }

        return true;
    }

    public static void main(String[] args) {
        String test1 = null;
        String test2 = "";
        String test3 = "   ";
        String test4 = "abc";

        System.out.println("Test1: " + isBlankOrEmpty(test1)); 
        System.out.println("Test2: " + isBlankOrEmpty(test2)); 
        System.out.println("Test3: " + isBlankOrEmpty(test3)); 
        System.out.println("Test4: " + isBlankOrEmpty(test4));
    }
}



/*
run:

Test1: true
Test2: true
Test3: true
Test4: false

*/

 



answered Jun 7, 2025 by avibootz
...