运行下面两端代码观察打印结果
public class Test {
public static void main(String[] args) {String str = "";
if(str == null || "".equals(str)){
System.out.println("----is---"+true);
}else{
System.out.println("----is---"+false);
}
if(str == null || str.trim().length()<=0){
System.out.println("----is---"+true);
}else{
System.out.println("----is---"+false);
}
}
}
打印结果:----is---true
----is---true
第二段代码:
public class Test {
public static void main(String[] args) {
String str = " ";
if(str == null || "".equals(str)){
System.out.println("----is---"+true);
}else{
System.out.println("----is---"+false);
}
if(str == null || str.trim().length()<=0){
System.out.println("----is---"+true);
}else{
System.out.println("----is---"+false);
}
}
}
打印结果
----is---false
----is---true
结论:如果使用 "".equals(str),就不能对“ ”进行判断,需要要下面这种,先去空,在判断长度,空串这样就逃不掉了。