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");
此问题的修复包括括号中的三元运算符:
// Works fine System.out.println("Value=" + (sb != null ? sb.toString() : "Null"));
这怎么可能?
A比07!高出 precedence.所以你首先评估“(Value =”sb)!= null.
精彩评论