先上一段报错的demo
@Test
public void testNull() throws Exception{
String str = null;
if (str.equals("youzhi")) {
System.out.println("121323");
}
}
会发现抛出空指针异常

因此判空方式应改为:
@Test
public void testNull() throws Exception{
String str = null;
if ("youzhi".equals(str)) {
System.out.println("121323");
}
}
原因个人理解为:在str进行判空的时候,本身为空,因此就出现了空指针。
代码中最佳的字符串判空方式为:
@Test
public void testNull() throws Exception{
String str = null;
/**
* 方式一
*/
if(str == null || "".equals(str)){
System.out.println("str is null");
}
/**
* 方式二
*/
if (StringUtils.isEmpty(str) || str.isEmpty()){
System.out.println("str is null");
}
}
Java空指针异常避免
本文通过一个简单的Java示例,介绍了如何避免空指针异常的发生,并提供了两种实用的字符串判空方法。第一种方法使用基本的条件判断,第二种方法借助了Apache Commons Lang库。
17万+

被折叠的 条评论
为什么被折叠?



