Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between heap memory and string pool [duplicate]

Tags:

java

string

What is the difference between heap memory and string pool in Java?

in this link , it is said that:

String s1 = "Hello";

String s2 = new String("Hello");

s1 points to String Pool's location and s2 points to Heap Memory location.

like image 388
OUN Saif Avatar asked Jan 28 '17 09:01

OUN Saif


2 Answers

StringPool is an area that the JVM uses to avoid redundant generation of String objects..

Those objects there can be "recycled" so you can (re)use them and so avoiding the "waste" of too much memory...

Consider the following example:

String s1 = "cat";

String s2 = "cat";

String s3 = new String("cat");

the JVM is smart enough to see that the object s2 is going to be assigned with the value "cat" which is already allocated in the memory(and assigned to the object "s1"), so instead of creating a new object and wasting that new memory place, it assign the reference to the same memory allocated for s1

enter image description here

like image 105
ΦXocę 웃 Пepeúpa ツ Avatar answered Nov 05 '22 11:11

ΦXocę 웃 Пepeúpa ツ


When you use String s = "Hello"; Sting s2= "Hello" you get the same copy for both s and s2. However, when you do String s = new String("Hello"); String s2 = new String("Hello") you have different copies for s and s2 in the heap.

like image 21
mc20 Avatar answered Nov 05 '22 10:11

mc20