Difference between heap memory and string pool
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.
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