In Java, concatenating a null string with another string does not throw a NullPointerException, as one might expect. Instead, the result is a new string with "null" prepended.
According to the Java Language Specification (JLS):
"If the reference [to the null string] is null, it is converted to the string 'null' (four ASCII characters n, u, l, l)."
Therefore, the null string is automatically converted to "null" before the concatenation takes place.
The compiler optimizes string concatenation to improve performance. It does this by using a StringBuilder object to accumulate the concatenation results.
When encountering a null string:
Consider the following code:
String s = null; s = s + "hello"; System.out.println(s); // prints "nullhello"
The compiler optimizes this code into the following equivalent:
s = new StringBuilder(String.valueOf(s)).append("hello").toString();
Since s is null, String.valueOf(s) returns "null", which is then appended to the StringBuilder and converted to a string.
The above is the detailed content of Why Doesn't Concatenating a Null String in Java Throw a NullPointerException?. For more information, please follow other related articles on the PHP Chinese website!