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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With