要检查Java中的字符串是否为空或为空,请使用==运算符。
假设我们有以下字符串。String myStr1 = "Jack Sparrow";
String myStr2 = "";
现在让我们检查两个字符串是否为null或为空。结果将为布尔值。res = (myStr1 == null || myStr1.length() == 0);
res = (myStr2 == null || myStr2.length() == 0);
示例public class Demo {
public static void main(String[] args) {
String myStr1 = "Jack Sparrow";
String myStr2 = "";
boolean res;
res = (myStr1 == null || myStr1.length() == 0);
System.out.println("String 1 is null or empty? "+res);
res = (myStr2 == null || myStr2.length() == 0);
System.out.println("String 2 is null or empty? "+res);
}
}
输出结果String 1 is null or empty? False
String 2 is null or empty? True