今天遇到一个bug,前端传来一个空值a,使用System.out.println(a == ""),打印了false。使用isEmpty()方法返回了true。这个地方比较容易混淆,特地来研究一下为什么。上代码。
public static void main(String[] args) throws Exception { String a = new String(); String b = ""; String c = null; if(a == "") System.out.println("a == ''"); if(a.isEmpty()) System.out.println("a is Empty"); if("".equals(a)) System.out.println("a equals ''"); if(b == "") System.out.println("b == ''"); if(b.isEmpty()) System.out.println("b is Empty"); if("".equals(b)) System.out.println("b equals ''"); //报java.lang.NullPointerException // if(c == "") // System.out.println("c == ''"); //报java.lang.NullPointerException // if(c.isEmpty()) // System.out.println("c is Empty"); if("".equals(c)) System.out.println("c equals ''"); }
控制台打印结果:
a is Empty
a equals ''
b == ''
b is Empty
b equals ''
分析:1.a是分配了内存空间,但是值为空,是绝对的空,是一种有值(值存在为空);
2.b是分配了内存空间,但是值为空字符串,是相对的空,是一种有值(值存在为空字符串);
3.c是为分配内存空间,无值,是一种无值(值不存在);
总结:在确定值不为null的情况下,可以使用isEmpty()来进行判断。
为null,不为null都可以使用"".equals(a)进行判断。
尽量避免使用a == "",进行判断。