问题
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
回答1:
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).
回答2:
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.
来源:https://stackoverflow.com/questions/19300193/concat-operation-on-string-and-null-keyword