Immutable nature of String – JAVA

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with 1 Comment on Immutable nature of String – JAVA

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.

Related posts

  • 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”.