[英]java String's immutability
If I run, 如果我跑步
String s1="abc";
then are there any differences between: 那么之间有什么区别:
String s2=new String(s1);
and 和
String s2="abc";
Here's what I'm confused about: 这就是我的困惑:
The Head First Java says:"If there's already a String in the String pool with the same value, the JVM doesn't create a duplicate, it simply refers your reference variable to the existing entry. " Which at my point of view is that the s1 has already created "abc",s2 just refers to it. Head First Java表示:“如果String池中已经存在一个具有相同值的String,则JVM不会创建重复项,它只是将您的引用变量引用到现有条目。”在我看来, s1已经创建了“ abc”,s2只是引用它。 Am I right?? 我对吗??
When you write String s2="abc";
当您编写String s2="abc";
and "abc"
is already in the pool, then you won't get a duplicate - you'll get a reference to the existing String
. 并且"abc"
已经在池中,那么您将不会得到重复-您将获得对现有String
的引用。
But if you write new String(something)
, you get a new String
, whether there's a matching String
in the pool or not. 但是,如果您编写new String(something)
,则无论池中是否有匹配的String
,您都会得到一个新的String
。
String Constant Pool comes into picture in this case as shown in below screenshot. 在这种情况下, 字符串常量池出现在图片中,如下面的屏幕快照所示。
I think it will help you to understand it visually. 我认为它将帮助您直观地理解它。
String s1="abc"; // s1 will go to String constant pool
String s2=new String(s1); // any object created by "new" keyword will go to Heap
String s2="abc"; // s1 and s2 both will refer to same string in constant pool
new关键字将强制在堆中创建一个新的字符串对象,即使它已经存在于字符串池中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.