Home > Java > javaTutorial > Why Doesn\'t Concatenating a Null String in Java Throw a NullPointerException?

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

Mary-Kate Olsen
Release: 2024-12-02 18:39:11
Original
698 people have browsed it

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

Concatenating Null Strings in Java

In Java, concatenating a null string with another string does not throw a NullPointerException, as one might expect. Instead, the result is a new string with "null" prepended.

Why is this the Expected Behavior?

According to the Java Language Specification (JLS):

"If the reference [to the null string] is null, it is converted to the string 'null' (four ASCII characters n, u, l, l)."

Therefore, the null string is automatically converted to "null" before the concatenation takes place.

How is this Behavior Implemented?

The compiler optimizes string concatenation to improve performance. It does this by using a StringBuilder object to accumulate the concatenation results.

When encountering a null string:

  • If the null string is the first argument, it calls String.valueOf() to convert it to a non-null string ("null").
  • If the null string is not the first argument, it appends the null string to the StringBuilder and then calls String.valueOf() on the result.

Example

Consider the following code:

String s = null;
s = s + "hello";
System.out.println(s); // prints "nullhello"
Copy after login

The compiler optimizes this code into the following equivalent:

s = new StringBuilder(String.valueOf(s)).append("hello").toString();
Copy after login

Since s is null, String.valueOf(s) returns "null", which is then appended to the StringBuilder and converted to a string.

The above is the detailed content of Why Doesn\'t Concatenating a Null String in Java Throw a NullPointerException?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template