Why does a null value appear in string output?

╄→гoц情女王★ 提交于 2019-11-27 04:07:44

问题


When I execute the following code the output is "nullHelloWorld". How does Java treat null?

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String str=null;
        str+="Hello World";
        System.out.println(str);
    }
}

回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/21893856/why-does-a-null-value-appear-in-string-output

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