Concatenation of String object and string literal

This is the next question from previous questions about string initialization in Java.

After some small tests in Java, I came across the following question:

Why can I execute this statement

String concatenated = str2 + " a_literal_string"; 

when the str2 a String object is initialized to null ( String str2 = null; ), but I can not call the toString() method on str2 ? Then how does Java concatenate a null String object and a string literal ?

By the way, I also tried combining the zero-initialized Integer and the string literal "a_literal_string" , and I got the same thing as "null a_literal_string" in the console. So, whatever null type does the same thing?

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

+5
java string null
source share
1 answer

This line:

 String concatenated = str2 + " a_literal_string"; 

compiled into something like

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

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

I tried also to combine the zero-initialized integer and the string literal "a_literal_string", and I got the same

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

+9
source share

All Articles