空字符串对象和字符串文字的串联 [英] Concatenation of a null String object and a string literal
问题描述
这是对一些之前关于 Java 中字符串初始化的问题的后续问题.
在 Java 中进行了一些小测试后,我面临以下问题:
After some small tests in Java, I'm facing the following question:
为什么我可以执行这个语句
Why can I execute this statement
String concatenated = str2 + " a_literal_string";
当 str2
一个 String
对象初始化为 null
(String str2 = null;
) 但我不能调用str2
上的 toString()
方法?那么Java是如何将一个空String对象和一个字符串字面量拼接起来的呢?
when str2
a String
object initialized to null
(String str2 = null;
) but I cannot call the method toString()
on str2
? Then how does Java do the concatenation of a null String object and a string literal?
顺便说一下,我还尝试将初始化为 null 的整数和字符串文字 "a_literal_string"
连接起来,我得到了与 "null a_literal_string" 相同的东西
代码>在控制台中.那么无论哪种 null 都会给出相同的结果?
By the way, I tried also to concatenate an Integer initialized to null and the string literal "a_literal_string"
and I've got the same thing that is "null a_literal_string"
in the console. So whichever kind of null gives the same thing?
PS : System.out.println(concatenated);
给出 null a_literal_string 作为控制台输出.
PS : System.out.println(concatenated);
gives null a_literal_string as output in the console.
推荐答案
这一行:
String concatenated = str2 + " a_literal_string";
被编译成类似
String concatenated = new StringBuilder().append(str2)
.append(" a_literal_string")
.toString();
这给出了 "null a_literal_string"
(而不是 NullPointerException
),因为 StringBuilder.append
是使用 String.valueOf
和 String.valueOf(null)
返回字符串 "null"
.
This gives "null a_literal_string"
(and not NullPointerException
) because StringBuilder.append
is implemented using String.valueOf
, and String.valueOf(null)
returns the string "null"
.
我还尝试将初始化为 null 的整数和字符串文字a_literal_string"连接起来,我得到了同样的东西
I tried also to concatenate an Integer initialized to null and the string literal "a_literal_string" and I've got the same thing
这和上面的原因是一样的.String.valueOf(anyObject)
其中 anyObject
为 null
将返回 "null"
.
This is for the same reason as above. String.valueOf(anyObject)
where anyObject
is null
will give back "null"
.
这篇关于空字符串对象和字符串文字的串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!