有多少String对象..? [英] How many String object..?

查看:93
本文介绍了有多少String对象..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我的朋友正在讨论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对象..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆