1

In Java 7 or below, if String is created using below syntax

String s1=new String("abc");

As per this link, Whenever we create a String Object, two objects will be created i.e. One in the Heap Area and One in the String constant pool and the String object reference always points to heap area object as shown below.

----------------------------------------------
|        Heap         | String Constant Pool |
|---------------------|-----------------------                      
|                     |                      |
|      "abc"          |       "abc"          |
|        ^            |                      |
|        |            |                      |
|       s1            |                      |

What will be the memory representation if we create another String object with the same value as

String s2=new String("abc");

And Will this create another object with same value in heap?
or it will just create object refering to String constant pool into heap ?

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 2
    `new` *always* creates a new instance. So you end up with a new string on the heap (pointed to by `s2`). – Andy Turner Apr 30 '18 at 12:08
  • Read here https://stackoverflow.com/questions/22473154/what-is-the-purpose-of-javas-string-intern – Anton Apr 30 '18 at 12:30
  • 1
    Possible duplicate of [What is the purpose of Java's String.intern()?](https://stackoverflow.com/questions/22473154/what-is-the-purpose-of-javas-string-intern) – Jim Mischel Apr 30 '18 at 13:35

1 Answers1

1
----------------------------------------------
|        Heap         | String Constant Pool |
|---------------------|-----------------------                      
|                     |                      |
|    "abc"  "abc"     |       "abc"          |
|      ^      ^       |                      |
|      |      |       |                      |
|     s1     s2       |                      |

As Andy Turner said, the new operator always produces a new instance. It is guaranteed by the JLS.

The only small wrinkle is that under certain circumstances (e.g. if escape analysis is enabled in certain JVM versions) the new operator might allocate an object on the stack rather than the heap.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216