5

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.

Community
  • 1
  • 1
Gab是好人
  • 1,976
  • 1
  • 25
  • 39
  • possible duplicate of [How Java do the string concatenation using "+"?](http://stackoverflow.com/questions/2721998/how-java-do-the-string-concatenation-using) – GhostCat Jun 08 '15 at 11:51
  • 2
    not really a duplicate, that question doesn't aim to the problem of null :) – Gab是好人 Jun 08 '15 at 11:59
  • Well, that question explains how "+" works. When you read that explanation, it becomes perfectly clear why "null + something" is working. – GhostCat Jun 08 '15 at 12:05
  • 1
    @Jägermeister, as far as I can tell, `String.valueOf` isn't even mention in those answers. That method is really key to understanding where `"null"` comes from. – aioobe Jun 08 '15 at 12:10

1 Answers1

9

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".

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • The answer in the related question you have given says String concatenation and StringBuilder.append() are totally different implementations. – Codebender Jun 08 '15 at 11:48
  • Hmm, could you clarify? String concatenation (using `+`) is implemented using `StringBuilder`. Where does it say something else? – aioobe Jun 08 '15 at 11:55
  • In the first answer in the link you gave, but the answer is wrong, at least for any post 1995 Java compiler. – David George Jun 08 '15 at 11:56
  • 1
    Ok, the quality of those answers wasn't top notch. Removed the link to that question. – aioobe Jun 08 '15 at 11:59