关于NullPointerException的小实例

时间: 2023-07-09 admin IT培训

关于NullPointerException的小实例

关于NullPointerException的小实例

先上一段报错的demo

    @Testpublic void testNull() throws Exception{String str = null;if (str.equals("youzhi")) {System.out.println("121323");}}

会发现抛出空指针异常

因此判空方式应改为:

    @Testpublic void testNull() throws Exception{String str = null;if ("youzhi".equals(str)) {System.out.println("121323");}}

原因个人理解为:在str进行判空的时候,本身为空,因此就出现了空指针。

代码中最佳的字符串判空方式为:

    @Testpublic 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");}}