The Enigma of Null String Concatenation
In Java, the concatenation of strings using the ' ' operator is a common operation. However, when one of the strings is null, unexpected behavior occurs that warrants further investigation.
Conflicting Expectations
The conventional wisdom would suggest that concatenating a null string should result in a NullPointerException. After all, null is often treated as an exceptional value in Java. However, in this case, the result is not an exception but a string containing "null".
Consider the following example:
String s = null; s = s + "hello"; System.out.println(s); // prints "nullhello"
This code prints "nullhello" rather than throwing a NullPointerException, defying our expectations.
Unveiling the Mechanics
To understand why this happens, we must delve into the Java Language Specification (JLS). According to the JLS, if one of the arguments in a string concatenation is null, it is automatically converted to the string "null" before performing the concatenation.
Implementation Details
To further unravel this mystery, we can examine the bytecode generated by the compiler for the above code. The compiler actually transforms the code into something equivalent to:
String s = null; s = new StringBuilder(String.valueOf(s)).append("hello").toString(); System.out.println(s); // prints "nullhello"
The StringBuilder class handles null values gracefully, allowing the concatenation to succeed without exception.
Compiler Optimization
It is worth noting that the JLS explicitly allows the compiler to optimize string concatenation for performance. In our example, the compiler could have used a more efficient approach, such as creating a StringBuffer directly and avoiding the intermediate String.valueOf() call.
Implications and Usage
This behavior has several implications for Java programmers:
The above is the detailed content of Why Does Java String Concatenation with Null Not Throw a NullPointerException?. For more information, please follow other related articles on the PHP Chinese website!