Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation of a null String object and a string literal

Tags:

java

string

null

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.

like image 519
Gab是好人 Avatar asked Jun 08 '15 11:06

Gab是好人


People also ask

Can you concatenate null to a string?

To concatenate null to a string, use the + operator. Let's say the following is our string. String str = "Demo Text"; We will now see how to effortlessly concatenate null to string.

Can you concatenate string literals?

String literalsThe code concatenates the smaller strings to create the long string literal. The parts are concatenated into a single string at compile time.

What happens when you concatenate null?

When SET CONCAT_NULL_YIELDS_NULL is ON, concatenating a null value with a string yields a NULL result. For example, SELECT 'abc' + NULL yields NULL .

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.


1 Answers

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

like image 128
aioobe Avatar answered Oct 11 '22 20:10

aioobe