Thursday, April 19, 2012

How String objects get stored in Memory?

String Object is immutable. Meaning: The object cannot be changed after it is created. Consider the following example.

String a = "hello" ; // lets assume this gets stored in address space &XYZ

When we append "world" to "hello" like below
a = a + "world";
The new String "hello world" will not replace the value "hello" in &XYZ but stored in a new address space &ZYX. Therefore, Variable "a" now points to the address &ZYX. Note that &XYZ does not get garbage collected (typically, objects get garbage collected when there is no reference to them anymore).

As a result, there are now two Strings in the Memory.
"hello" and "hello world"

So, we have to be careful when appending the string objects as the memory foot print rapidly increases with every string modification. Further, String objects are not garbage collected after their usage but are kept in the memory pool for later re-use.

There is a separate string memory pool different from standard pool where all String Objects are stored. If two strings with the same value are created, the second string and the first string point to the same address space thus reusing the memory space.

Ex:
String a = "hello";
String b = "hello";
In the above case, both "a" and "b" point to the same address &XYZ.
a = a + "world";
Now, a will point to address &ZYX while b will continue to point to &XYZ address.

Alternative to String: StringBuffer and StringBuilder are Mutable Objects. Consider using these if there is a need for too many string modifications in your code base.

4 comments:

  1. Good explanation But satisfied .
    You need to explain detailed about String Pool and Java Heap where the string stores and how it reuses it reference..

    ReplyDelete
  2. Hi Rahul. Thanks for the feedback. I will cover the topics you mentioned.

    ReplyDelete
  3. Hi Rahul. Thanks for the feedback. I will cover the topics you mentioned.

    ReplyDelete
  4. Hi Rahul. Thanks for the feedback. I will cover the topics you mentioned.

    ReplyDelete