Immutable nature of String – JAVA

Immutable nature of string is charecterised by it’s property that one’s a memory location is reserved (allocated) to a string  and if string value changes then old value is not over written by new one.

Lets discuss it,

For example : Create an instance of type String as s1.

Create instance of string in JAVA

It will reserve a memory location in Heap Memory with s1 storing the address of memory location as shown,

Immutable String in JAVA

Now let’s change the content of s1 ,in case of primitive data type like int, float , char etc .If we change the containt  of one variable the privious value is overwritten by the new value, but in case of String type instances this is not possible ,here a new memeory  location is created which will point to the new value as shown..

Immutable String in JAVA

So new memory location is created for storing new value (new string)

Immutable String JAVA

This behavior of String Instances is reffered as Immutable nature of String.

Posted

in

by

Tags:


Related Posts

Comments

One response to “Immutable nature of String – JAVA”

  1. Pralay Avatar
    Pralay

    Shiva, if you create a String “not”using new, it will be placed in the string pool.
    String trialString = “My name is Pralay”; // this is not placed in heap, goes to string literal pool
    String bString = new String(“I am a Masters, Comp Sci student at Univ. of California”; //This does a heap memory allocation since we have used a “new”.
    Thanks.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading