Search code examples
javastringobjectheap-memorystring-pool

Where will be the newly created String? Heap memory or String constant pool?


As per Java,

There are two places in which strings are stored. String literal pool and heap memory according to its creation. I need to know, when assignment of string is done to another string, where does the newly created string will be stored?

I've done the assignment operations on both the type of Strings which are there in heap as well as in string pool. I got results like this.

    String str = new String("foo"); ===> str is created in heap memory
    String strL = "doo"; ===> strL is created in String pool.

But when,

    String strNew = strL; // strL which is there in String Pool is assigned to strNew.

Now, If I do this

    strL = null;
    System.out.println(strNew)// output : "doo".
    System.out.println(strL)// output : null.

Similarly,

    String strNewH = str; // str which is there in heap is assigned to strNewH

Now,

    str = null;
    System.out.println(strNewH);// output : "foo".
    System.out.println(str); // null

Above is the output I have got on IDE. According to this output, a new referenced object for strNew is created in string pool and a new referenced object for strNewH is created in heap. Is it correct?


Solution

  • You have a few misconceptions.

    The string pool is also part of the heap. You probably meant to ask whether the strings are in the string pool or some other part of heap.

    You also seem to think that assignments create new objects. They don't. Variables and objects are separate things. After these two lines:

    String str = new String("foo");
    String strL = "doo";
    

    The variable str refers to a string object "foo", that is not in the string pool. The variable strL refers to a string object "doo", that is in the string pool.

    (Note the word "refers")

    When you assign String variables, you are simply changing what they refer to. Here:

    String strNew = strL;
    

    You are making strNew refer to the same object as the object that strL refers to.

    Similarly, when you set something to null, you make it refer to nothing. The object it was referring to is not necessarily destroyed.

    So as for your question:

    According to this output, a new referenced object for strNew is created in string pool and a new referenced object for strNewH is created in heap. Is it correct?

    No, it is not correct. There are no new objects created. strNew refers to "doo", which is in the string pool, and is the same object as the one that strL was referring to. strNewH refers to "foo", which is not in the string pool, and is the same object as the one that str was referring to.