Why does a null value appear in string output?

谁说胖子不能爱 提交于 2019-11-27 16:14:15

You are attempting to concatenate a value to null. This is governed by "String Conversion", which occurs when one operand is a String, and that is covered by the JLS, Section 5.1.11:

Now only reference values need to be considered:

  • If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

When you try to concat null through + operator, it is effectively replaced by a String containing "null".

A nice thing about this is, that this way you can avoid the NullPointerException, that you would otherwise get, if you explicitly called .toString() method on a null variable.

Java treats null as nothing, it is the default value of a String. It appears in your String output because you use += to add "Hello World" to str.

String str=null;
str+="Hello World";
System.out.println(str);

You are basically telling Java: give my str variable the type of String and assign it the value null; now add and assign (+=) the String "Hello World" to the variable str; now print out str

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