关于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");}}
最新文章
- 老鼠走迷宫算法
- java.lang.NullPointerException: null的错误
- (转自林达华)深入问题本身
- WinRAR 3.933.92 的注册码(已经测试)
- linux 下dump文件放在那里,怎么查看dump文件目录
- 所有结点对的最短路径问题之Johnson算法
- 大数定律的形象理解
- 叶片杰伦恋夜语
- 电话银行
- Linuxmmap
- 高通Linux Android 平台中的蓝牙功能学习 (4)
- C# WebForm
- schedulewithfixeddelay
- linux终端基本操作命令
- [转载]interp1
- 这些响应式网页测试工具确保你的设计万无一失
- Shiro系统权限管理、及原理剖析