Java:在代码中创建了多少个对象? [英] Java: How many objects are created in the code?
问题描述
在以下代码中创建了多少个对象?
How many objects are created in the following code?
String a, b, c;
a = "1234";
b = a;
c = a + b;
有人告诉我答案是 2
,因为只有a和b指向自己的数据.
I was been told the answer is 2
, because only a and b point to their own data.
c
仅使用 a
和 b
创建.但是,声明变量不是创建吗?这个问题含糊吗?我说了 3
.
c
is only created from using a
and b
. However, isn't the act of declaring a variable considered creating it? Is this question vague? I said 3
.
推荐答案
a ="abcd"
创建一个 String
对象,并将其初始化为值"abcd".那是一个对象
a = "abcd"
creates a String
object, and initializes it with the value "abcd". So that's one object
b = a
使 b
指向与 a
相同的位置,因此 a + b
将创建一个新对象,然后将其分配给 c
.总共创建了两个对象
b = a
makes b
point to the same spot as a
, so then a + b
will create a new object, which is then assigned to c
. That makes a total of two objects created
这篇关于Java:在代码中创建了多少个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!