java 与 Null 的字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4199298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:16:42  来源:igfitidea点击:

String concatenation with Null

javastring

提问by oshai

I have the following code

我有以下代码

System.out.println("" + null);

and the output is null.
How does Java do the trick in string concatenation?

并且输出是null
Java 如何实现字符串连接?

回答by oxbow_lakes

Because Java converts the expression "A String" + xto something along the lines of "A String" + String.valueOf(x)

因为 Java 将表达式转换"A String" + x为类似于"A String" + String.valueOf(x)

In actual fact I think it probably uses StringBuilders, so that:

实际上,我认为它可能使用StringBuilders,因此:

"A String " + x + " and another " + y

resolves to the more efficient

解决更有效的问题

new StringBuilder("A String ")
    .append(x)
    .append(" and another ")
    .append(y).toString()

This uses the appendmethods on String builder (for each type), which handle nullproperly

这使用appendString builder 上的方法(对于每种类型),这些方法可以null正确处理

回答by Alexander Pogrebnyak

Java uses StringBuilder.append( Object obj )behind the scenes.

JavaStringBuilder.append( Object obj )在幕后使用。

It is not hard to imagine its implementation.

不难想象它的实现。

public StringBuilder append( Object obj )
{
   if ( obj == null )
   {
       append( "null" );
   }
   else
   {
       append( obj.toString( ) );
   }

   return this;
}

回答by Nathan Hughes

The code "" + nullis converted by the compiler to

代码"" + null由编译器转换为

new StringBuffer().append("").append(null);

and StringBuffer replaces null with the string "null". So the result is the string "null".

并且 StringBuffer 将 null 替换为字符串“null”。所以结果是字符串“null”。