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

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
  • 2
    Duplicate http://stackoverflow.com/questions/2486191/java-string-pool – Pankaj Gadge May 06 '14 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. – ajb May 06 '14 at 23:09

3 Answers3

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.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • 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. – user3298812 May 06 '14 at 23:09
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

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • 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 !!!! – user3298812 May 06 '14 at 23:17
  • "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. – Braj May 06 '14 at 23:23
  • I hope you got it now and will remember for you next JAVA interview. :) – Braj May 06 '14 at 23:28
1

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

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125