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;
}
}
Bad practice, why just not return str != null && str.trim()… ??
str.trim() return a String not a boolean.
” “.trim() return “”
Ignorance.