先上一段报错的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");
}
}