Concatenating Null Strings in Java
In Java, concatenating null strings may seem counterintuitive, leading to the expectation of a NullPointerException. However, this operation successfully executes, resulting in a string containing "null" followed by the concatenated string.
Why does this work?
According to the Java Language Specification (JLS) 8, § 15.18.1, null references are explicitly converted to the string "null" during string concatenation. This conversion occurs before any method invocations, ensuring that NullPointerExceptions are not thrown.
How does it work?
The Java compiler transforms the concatenation expression into an equivalent sequence of method calls. In the case of s = s "hello", the compiler generates code similar to:
s = new StringBuilder(String.valueOf(s)).append("hello").toString();
The append method of StringBuilder handles null arguments gracefully. If null is the first argument, String.valueOf() is invoked to convert it to a string.
Alternatively, the expression s = "hello" s would be transformed into:
s = new StringBuilder("hello").append(s).toString();
In this case, the append method takes null as the second argument and delegates it to String.valueOf().
Note:
Java compilers may optimize string concatenation differently to improve performance, using techniques such as StringBuilder pooling. Therefore, the exact equivalent code generated may vary depending on the compiler used.
The above is the detailed content of Why Doesn't Concatenating Null Strings in Java Throw a NullPointerException?. For more information, please follow other related articles on the PHP Chinese website!