Java – Check if a String is empty or null

In Java, we can use (str != null && !str.isEmpty()) to make sure the String is not empty or null.

StringNotEmpty.java

package com.mkyong;

public class StringNotEmpty {

    public static void main(String[] args) {

        System.out.println(notEmpty(""));      // false
        System.out.println(notEmpty(null));    // false
        System.out.println(notEmpty("hello")); // true
        System.out.println(notEmpty(" "));     // true, a space...

    }

    private static boolean notEmpty(String str) {
        if (str != null && !str.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

}

Output


false
false
true
true

If we want empty space like notEmpty(" ") to return false, update the code with .trim(),


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

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar