java String's immutability

可紊 提交于 2019-12-13 05:18:57

问题


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. Am I right??


回答1:


When you write 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.

But if you write new String(something), you get a new String, whether there's a matching String in the pool or not.




回答2:


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




回答3:


the new keyword will force to create a new string object in heap even it already exist in string pool



来源:https://stackoverflow.com/questions/23505952/java-strings-immutability

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!