Java String 对象创建 [英] Java String object creation

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

问题描述

我一直在阅读 Java String 对象,我有这个问题 -

I have been reading Java String object and I had this question -

String x="a";
String y="b";

它是否在 Java 中创建了两个对象?

Does it create two objects in Java?

推荐答案

每当使用 new 运算符初始化 String 时,就会创建它的新对象.就像你这样做

When ever a String is initialized using new operator its new object is created. Like if you do

String s1= new String("string");

String s1= new String ("string");

String s2=new String("string");

String s2=new String ("string");

String s3=new String("string");

String s3=new String ("string");

这三个都将在堆中创建一个单独的 String 对象.而如果上述所有字符串都是在没有 new 运算符的情况下初始化的,那么首先将在字符串池中检查该字符串是否存在.如果需要的字符串存在,那么新的引用将开始指向现有的字符串.否则它将在池中创建新的字符串.例如:

All of the three will create a separate String object in the heap. Whereas if all the above strings are initialized without new operator then, firstly the string will be checked in string pool for its existence. If required string exist then the new reference will start pointing to the existing string.Otherwise it will create new sting in the pool. For example:

String s1="字符串";

String s1= "string";

字符串 s2="字符串";

String s2="string";

字符串 s3="string1";

String s3="string1";

在上面的例子中,字符串池中只会创建两个字符串(string"和string1").其中,字符串 s1 和 s2 将引用单个对象字符串",而 s3 将引用另一个字符串对象字符串1".

In the above example only two string will be created in string pool ("string" and "string1"). Where String s1 and s2 will refer to single object "string" and s3 will refer to another string object "string1".

这篇关于Java String 对象创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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