为什么在字符串输出中出现空值? [英] Why does a null value appear in string output?

查看:202
本文介绍了为什么在字符串输出中出现空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行以下代码时,输​​出为"nullHelloWorld". Java如何处理null?

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);
    }
}

推荐答案

您正在尝试将值连接到null.这由字符串转换"控制,该字符串转换在一个操作数为String时发生,并由

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:

  • 如果引用为空,则将其转换为字符串"null". (四个ASCII字符n,u,l,l).

这篇关于为什么在字符串输出中出现空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆