"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Doesn\'t Concatenating Null Strings in Java Throw a NullPointerException?

Why Doesn\'t Concatenating Null Strings in Java Throw a NullPointerException?

Published on 2024-11-17
Browse:116

Why Doesn\'t Concatenating Null Strings in Java Throw a NullPointerException?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3