Why String Is Immutable In Java!!!

Mahinsa Bhanuka
3 min readApr 19, 2022

--

In java “Java Strings are Immutable” term is a popular thing. actually, what does that mean?

Simple as that immutable means once you declare a string variable we cannot modify it. So When you create a java string it’s unchangeable or unmodifiable. Objects in Java are created in heap memory. Java string is also an object type but it has a special memory area to store strings in Java. it is known as String Pool. Here is some example to understand that.

As an example when we declared a string variable like this,

String name = “Bhanuka”;

This is how strings are stored in string pool.
How Strings Are Stored In Memory.

That name variable refers to the String Object “Bhanuka”. When we want to add another variable with the same object as “Bhanuka”, what will happen? Java Creates a brand new object for that? let’s discuss that.

String name = “Bhanuka”;

String name2 = “Bhanuka”;

It does not create a brand new object for that, name2 also refers to the same object “Bhanuka” inside the string pool. if we declared 1000 times with the same string object that is already in the string pool, that will always refer to the same String object. In this example, name and name2 both variables are refers to “Bhanuka” object in the string pool. if we changed our name variable with “Kamal” What will happen?

The string object “Bhanuka” was not replaced with the string object “Kamal”, It creates a brand new Object “Kamal” inside the String pool and the name variable reference is changed to that object “Kamal”. Once we created an object we can not modify that. That’s why strings are immutable.

String name = “Bhanuka”

name.concat(“Kamal”);

System.out.print(name);

What do you think ? here we simply used concat() method to concatenate “Kamal” String Object.

A new string object “Bhanuka Kamal” will be created inside the pool. but the “Bhanuka” Object and name variable still refer to that “Bhanuka” Object. Here the output will be “Bhanuka”, not the “Bhanuka Kamal”. if you want to create a brand new object with same object name you can use this method.

String name = “Bhanuka”
String name1 = new String(“Bhanuka”);

Thank You!!!

--

--