Concatenation of Null Strings in Java
In Java, concatenating a null string with another string does not result in a NullPointerException. This behavior may appear surprising, but it is defined by the Java Language Specification (JLS).
Why does concatenation succeed for null strings?
According to JLS 5, Section 15.18.1.1, when a reference is null, it is converted to the string "null" before concatenation. This conversion is performed automatically by the compiler.
How does concatenation with null strings work?
Behind the scenes, the compiler optimizes the concatenation operation to use a StringBuilder, which can efficiently handle null values. In the bytecode, the equivalent code for concatenating a null string "s" with the string "hello" is:
String s = null; s = new StringBuilder(String.valueOf(s)).append("hello").toString();
The StringBuilder constructor takes the converted value of the null string, which is "null", and appends it to the string "hello" to create the final string "nullhello".
Note: String concatenation is one of the few optimizations that the Java compiler is allowed to perform. The precise implementation may vary depending on the compiler used, but the behavior of null concatenation remains consistent.
The above is the detailed content of How Does Java Handle String Concatenation with Null Values?. For more information, please follow other related articles on the PHP Chinese website!