奇怪的空指针异常情况:三元条件运算符不适用于字符串连接 [英] Strange Null pointer exception case: ternary conditional operator not working with string concatenation
本文介绍了奇怪的空指针异常情况:三元条件运算符不适用于字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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");
此问题的修复包括括号中的三元运算符:
The fix for this issue is encompassing the ternary operator in brackets:
// Works fine
System.out.println("Value=" + (sb != null ? sb.toString() : "Null"));
这怎么可能?
推荐答案
A +
有更高的 优先 比 !=
.
A +
has a higher precedence than a !=
.
所以你首先评估 "(Value="+sb ) != null
.
这篇关于奇怪的空指针异常情况:三元条件运算符不适用于字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文