简体   繁体   中英

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

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.

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关键字将强制在堆中创建一个新的字符串对象,即使它已经存在于字符串池中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM