0

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??

2
  • 2
    Duplicate stackoverflow.com/questions/2486191/java-string-pool Commented May 6, 2014 at 23:03
  • As far as I'm concerned, there is never a legitimate reason to write String s2 = new String(s1);. You should not be writing code that depends on two string references being unequal even though the contents are equal. And if you don't, then String s2 = s1; works just as well. Commented May 6, 2014 at 23:09

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly!!!That's what I thought about. Thanks for making sure about that. Since the "CS61B data structure" at Berkeley says they are the same....I think he just said that by mistake.
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

enter image description here

3 Comments

you said any object created by "new" will go to Heap, but why str1 is in the Constant Pool but not in the Heap?Can you explain the whole process for the first line"String str1=new String("java5")"?Thanks a lot !!!!
"java5" is a string literal that will go the string constant pool. have you noticed variable str1 in diagram at top position that is inside the heap.
I hope you got it now and will remember for you next JAVA interview. :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.