内存中将创建多少个字符串对象? [英] How many string objects will be created in memory?
本文介绍了内存中将创建多少个字符串对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码将创建多少个字符串对象?
How many string objects will be created by the following code?
String s="";
s+=new String("a");
s+="b";
我在考试中遇到了这个问题。我想知道正确的答案。我说了2个对象。
池中包含,b的对象和新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
- 通过连接<$创建的字符串c $ c> 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"
.
如果您假设已经由先前加载的代码创建了三个字符串文字,则代码段会创建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.
这篇关于内存中将创建多少个字符串对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文