简体   繁体   中英

Concat operation on string and null keyword

As per my understanding, when + operator is used with two string literals, concat method is invoked to produce the expected string. Example - String s = "A" + "B";

When there is null in place of one literals as below then it is generating below output. I am confused here - why it is not throwing NullPointerException ?

    String str = null + "B";
    System.out.println(str);

Output:

nullB

why it is not throwing NullPointerException .

Because, string concatenation applies string conversion operation to the operand which is not of type String , which is null reference in this case. The string concatenation is converted to:

String str = new StringBuilder("null").append("B").toString();

which wouldn't throw a NPE .

From JLS §5.1.11 - String Conversion :

This reference value is then converted to type String by string conversion. [...]

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

Because you are concatenating two strings, str is not null. When you use + for joining the two strings, it takes null to be a string too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM