Java – strange null pointer exception: ternary conditional operators do not use string concatenation
•
Java
StringBuffer sb=null;
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");
Fixes to this issue include ternary operators in parentheses:
// Works fine System.out.println("Value=" + (sb != null ? sb.toString() : "Null"));
How is this possible?
Solution
A than 07! Higher than precedence
So you first evaluate "(value =" sb)= null.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码