Reputation: 521
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
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 charactersn
,u
,l
,l
).
Upvotes: 6
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