Concat operation on string and null keyword

前提是你 提交于 2020-01-15 08:59:11

问题


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 characters n, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!