Question
Why doesn't concatenating a null string in Java throw a NullPointerException?
String s = null;
s = s + "hello";
System.out.println(s); // prints "nullhello"
Answer
In Java, when you concatenate a null reference with a string using the '+' operator, the null gets converted to the string 'null' by the compiler. This behavior is specific to how Java handles string concatenation and does not raise a NullPointerException as one might expect.
// Correct way to avoid null in concatenation
String s = null;
if (s != null) {
s = s + "hello";
} else {
s = "hello";
}
System.out.println(s); // Prints "hello"
Causes
- Java treats null as a string when using the '+' operator for concatenation.
- The Java compiler automatically converts null to the string "null" during concatenation.
Solutions
- Use a string check to avoid concatenating null, e.g., \nif (s != null) { s = s + "hello"; }
- Alternatively, initialize the string with an empty string: String s = "";
Common Mistakes
Mistake: Assuming that concatenation with null will throw an exception.
Solution: Understand that null is converted to the string 'null' in concatenation.
Mistake: Not checking if a string is null before concatenation, leading to unwanted results.
Solution: Always check if the string is null before concatenating to improve clarity.
Helpers
- Java String concatenation
- NullPointerException in Java
- Concatenating null string Java
- Java string behavior with null