equals所引出的空指针异常

equals所引出的空指针异常”java.lang.NullPointerException”

空指针异常是平常遇到算是很头痛的异常了
通常我们比较字符串是否相等,我们会用equals来比较;
其实这其中便隐含了一个空指针异常,让我们来运行一下,下面的代码吧!
String a =null;
System.out.println(a.equals("3"));

已知的变量去比未知变量其实解决这个问题的办法很简单,我们只需要用已知的变量去比未知变量就可以了
String a =null;
System.out.println("3".equals(a));

因为a=null,没有在内存中开辟空间,用一个什么都没有的东西去比较,自然会是不对的

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×