Concatenation of a null String object and a string literal

久未见 提交于 2020-01-03 12:28:10

问题


This is a follow-up question to some previous questions about String initialization in Java.

After some small tests in Java, I'm facing the following question:

Why can I execute this statement

String concatenated = str2 + " a_literal_string";

when str2 a String object initialized to null (String str2 = null;) but I cannot call the method toString() on str2? Then how does Java do the concatenation of a null String object and a string literal?

By the way, I tried also to concatenate an Integer initialized to null and the string literal "a_literal_string" and I've got the same thing that is "null a_literal_string" in the console. So whichever kind of null gives the same thing?

PS : System.out.println(concatenated); gives null a_literal_string as output in the console.


回答1:


This line:

String concatenated = str2 + " a_literal_string";

is compiled into something like

String concatenated = new StringBuilder().append(str2)
                                         .append(" a_literal_string")
                                         .toString();

This gives "null a_literal_string" (and not NullPointerException) because StringBuilder.append is implemented using String.valueOf, and String.valueOf(null) returns the string "null".

I tried also to concatenate an Integer initialized to null and the string literal "a_literal_string" and I've got the same thing

This is for the same reason as above. String.valueOf(anyObject) where anyObject is null will give back "null".



来源:https://stackoverflow.com/questions/30708308/concatenation-of-a-null-string-object-and-a-string-literal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!