字符串连接与Null [英] String concatenation with Null

查看:147
本文介绍了字符串连接与Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

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

,输出 null

Java如何在字符串连接中完成这个技巧?

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

推荐答案

因为Java转换表达式字符串+ x A String+ String.valueOf(x)

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

实际上我认为它可能使用 StringBuilder s,所以:

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

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

解析为效率更高

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

这使用String构建器上的追加方法(对于每种类型),正确处理 null

This uses the append methods on String builder (for each type), which handle null properly

这篇关于字符串连接与Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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