分配和创建字符串实例之间有什么区别? [英] What is the difference Between Assignment and Creating Instance of String?

查看:99
本文介绍了分配和创建字符串实例之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在面试问题中,采访者问我

In an interview question, Interviewer asked me

以下陈述之间的共同点和区别是什么:

What is the common and difference between the following statements:

String s = "Test";

String s = new String("Test");

内存分配有什么不同吗?

Is there any difference in memory allocation?

推荐答案

String s = "Test"; 

首先在字符串常量池中查找字符串Test。如果发现s将被引用以找到找到的对象。如果未找到,则创建一个新的String对象,添加到池中,并使s引用新创建的对象。

Will first look for the String "Test" in the string constant pool. If found s will be made to refer to the found object. If not found, a new String object is created, added to the pool and s is made to refer to the newly created object.

String s = new String("Test");

首先会创建一个新的字符串对象并让它引用它。另外,字符串Test的条目在字符串常量池中生成,如果它还没有。

Will first create a new string object and make s refer to it. Additionally an entry for string "Test" is made in the string constant pool, if its not already there.

所以假设字符串Test不在池中,第一个声明将创建一个对象,而第二个声明将创建两个对象。

So assuming string "Test" is not in the pool, the first declaration will create one object while the second will create two objects.

这篇关于分配和创建字符串实例之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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