Sid*_*Sid 3 java nullpointerexception
StringBuffer sb=null;
// Some more logic that conditionally assigns value to the StringBuffer
// Prints Value=null
System.out.println("Value="+sb);
// Throws NullPointerException
System.out.println("Value=" + sb != null ? sb.toString() : "Null");
Run Code Online (Sandbox Code Playgroud)
此问题的修复包括括号中的三元运算符:
// Works fine
System.out.println("Value=" + (sb != null ? sb.toString() : "Null"));
Run Code Online (Sandbox Code Playgroud)
这怎么可能?
让我们用破坏的花瓶中的编译器有效的方式来表达表达式:
System.out.println( ("Value" + sb != null) ? sb.toString() : "Null");
Run Code Online (Sandbox Code Playgroud)
现在"Value" + sb永远不会为null,即使sb是null ...所以当sb 为 null时,它正在调用toString()并且正在进行中.
| 归档时间: |
|
| 查看次数: |
913 次 |
| 最近记录: |