java 如何检查
检查空字符串
使用 isEmpty() 方法检查字符串是否为空。该方法返回 true 如果字符串长度为0,否则返回 false。
String str = "";
if (str.isEmpty()) {
System.out.println("字符串为空");
}
检查 null 字符串
使用 == 操作符检查字符串是否为 null。

String str = null;
if (str == null) {
System.out.println("字符串为 null");
}
检查空白字符串
使用 isBlank() 方法(Java 11+)检查字符串是否为空白(仅包含空格、制表符等空白字符)。
String str = " ";
if (str.isBlank()) {
System.out.println("字符串为空白");
}
组合检查
通常需要同时检查字符串是否为 null 或空/空白。

String str = null;
if (str == null || str.isEmpty()) {
System.out.println("字符串为 null 或空");
}
使用 Apache Commons Lang
Apache Commons Lang 库提供 StringUtils 类,包含更便捷的方法。
import org.apache.commons.lang3.StringUtils;
String str = null;
if (StringUtils.isEmpty(str)) {
System.out.println("字符串为 null 或空");
}
if (StringUtils.isBlank(str)) {
System.out.println("字符串为 null 或空白");
}
使用 Guava
Guava 库提供 Strings 类,同样可以简化检查。
import com.google.common.base.Strings;
String str = null;
if (Strings.isNullOrEmpty(str)) {
System.out.println("字符串为 null 或空");
}






