0

According to Kathy Sierra's book:

String s = "abc"; // creates one String object and one
// reference variable

In this simple case, "abc" will go in the pool and s will refer to it.

String s = new String("abc"); // creates two objects,
// and one reference variable

In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and s will refer to it. In addition,the literal "abc" will be placed in the pool.


As I know, when we use literals, it stores value in pool but when we use new keyword it creates object in heap. Here I want to know, is the heap object refer pool data (String) or not?

matt
  • 78,533
  • 8
  • 163
  • 197
raw
  • 409
  • 1
  • 5
  • 11
  • 4
    This topic has been beaten to death -- there are easily 20 dupes if someone has the energy to search. – Hot Licks Jan 16 '15 at 18:53
  • @HotLicks 20 dupes that were closed as dupes of ~10000000 topics. – Maroun Jan 16 '15 at 18:54
  • possible duplicate of [Java Strings: "String s = new String("silly");"](http://stackoverflow.com/questions/334518/java-strings-string-s-new-stringsilly) – wassgren Jan 16 '15 at 18:56
  • It depends on which version of Java you have. Before around Java 7 update 25, the heap object would have pointed, internally, at the pool (interned) object. After about update 25, this was changed so that `new String` always copied data into its own buffer, so there was never a reference to another object internally. – markspace Jan 16 '15 at 18:56
  • @markspace - An interned String is still in the heap, it's just a permanent resident of the heap. What may have changed in 7 is that they finally gave up "sharing" the `char[]` array between the interned String and any `new` copies made of that String. – Hot Licks Jan 16 '15 at 19:04
  • 2
    With JDK 1.8.25 this question becomes interesting again. Because of the String deduplication the string copy will be removed soon. Its a pity that this does not work for SO questions yet... – Cfx Jan 16 '15 at 19:12

1 Answers1

-1

The variable you created using new String("abc") is not the same as the pool "abc" string.

String string1 = "abc";
String string2 = new String("abc");
System.out.println(string1.equals(string2)); //will print true
System.out.println(string1 == string2); //will print false
brso05
  • 13,142
  • 2
  • 21
  • 40