本文介绍了将在内存中创建多少个字符串对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码会创建多少个字符串对象?
How many string objects will be created by the following code?
String s="";
s+=new String("a");
s+="b";
我在考试时遇到了这个问题.我想知道正确答案.我说的是 2 个对象.
池中包含 "" 、 "b" 的对象和 new String("a") 创建的对象;
I had this question at exam. I want to know the right answer . I said 2 objects.
The object from pool that contains "" , "b" and the object created by new String("a");
推荐答案
我将回答另一个更清晰的问题:以下代码片段中涉及多少 String 实例:
I'll anwser to another, clearer question: how many String instances are involved in the following code snippet:
String s="";
s+=new String("a");
s+="b";
答案是 6:
- 空字符串字面量:
""
; - 字符串文字
"a"
; - 字符串文字a"的副本:
new String("a")
; - 通过连接
s
和"a"
的副本创建的字符串; - 字符串文字
"b"
- 通过连接
s
和"b"
创建的字符串.
- the empty String literal:
""
; - the String literal
"a"
; - the copy of the String literal "a":
new String("a")
; - the String created by concatenating
s
and the copy of"a"
; - the String literal
"b"
- the String created by concatenating
s
and"b"
.
如果您假设之前加载的代码已经创建了三个 String 字面量,则代码片段因此创建了 3 个新的 String 实例.
If you assume that the three String literals have already been created by previously-loaded code, the code snippet thus creates 3 new String instances.
这篇关于将在内存中创建多少个字符串对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!