Main Tutorials

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 Author

author image
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

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Your shadow
3 years ago

Bad practice, why just not return str != null && str.trim()… ??

lagerbie
2 years ago
Reply to  Your shadow

str.trim() return a String not a boolean.

” “.trim() return “”

Guest
3 years ago
Reply to  Your shadow

Ignorance.