我和我的朋友正在讨论Strings,我们坚持这个:
Me and my friend was discussing on Strings and we stuck on this:
String str = "ObjectOne"+"ObjectTwo";他说将创建三个对象,我说将创建一个对象。
He says total three Object will be created and I say one object will be created.
他对3个对象的逻辑是:一个用于ObjectOne,一个用于ObjectTwo,第三个是两个String对象的连接版本。
His logic behind 3 objects is: one for "ObjectOne" and one for "ObjectTwo" and third one is the concatenated version of two String objects.
我在一个对象后面的逻辑是在编译时,字符串对象将在字节代码中连接起来:
My logic behind one object is at compile time both the string objects will be concatenated in the byte code as:
String str = "ObjectOneObjectTwo";在运行时,只会以这种方式创建一个对象。这背后的真相是什么。
And at run time only one object will be created in such a way. What is the truth behind this.
推荐答案如果你写(文字或常量)
If you write(literals or constants)
String str = "ObjectOne"+"ObjectTwo";相当于
String str = "ObjectOneObjectTwo"; // compiler optimize it so one Object更多推荐
有多少String对象..?
发布评论