Juns
Juns

Reputation: 521

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

Upvotes: 2

Views: 1494

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213223

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

Upvotes: 6

DT7
DT7

Reputation: 1609

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.

Upvotes: 4

Related Questions