“String in Java is immutable” is it right?

Harshana Samarasinghe
CodeX
Published in
3 min readApr 11, 2022

Well, I’m sure most of you already know!!! I was familiar with that as well!!! But did we get the keyword “immutable” exactly, and do we know why Strings in Java are immutable?

Let’s just get started!!!

What is immutable?

An object can’t be edited or modified after it has already been created. In Java, a value and an object are two separate concepts. An instant variable or a reference variable keeps value. An instant variable stores the real value (depending on the type) that a programmer, for example, delivers.

int x = 53;
double s = 43.725;
String name = “Kasun”;

Objects in Java are stored in the Heap area of the memory of the JVM, as you may know. As a result, the value of a reference variable is the memory address of the object it is pointing to. A reference variable “S” is represented in the diagram below.

An object, on the other hand, is a subclass of a class with several instance variables known as “properties.”

The String class represents character strings in Java. As a result, any variable declared with the type “String” becomes a reference variable that points to a String class instance (ex-: String object). The value “Alex” is assigned to the variable “name” as seen below. We later change the variable’s value to “Lucas” Only the values of the reference variable “name” are altered in this case. The String object isn’t modified at all. The “John” object is the String Object to which we are referring.

String name = “Alex”;
name = “Lucas”;

Alright, I get it. You’re puzzled. Let’s take a look at what happens in the stack and heap memory locations for the code above!!!

As explained previously, any Java object is stored in the Heap. JVM generates an object in the Heap and sets its value to “Alex” when the “name” variable is set to “Alex” (because a String value is assigned, String is a class in Java, so that a String object gets created). This object is referenced by the “name” variable. This is shown in the diagram below.

When “name” is allocated to “Lucas” afterwards. This generates a new String object with the value “Lucas.” So, where does the “name” variable now point? Absolutely, as can be seen here, the “name” variable dereferences from the “Alex” object and points to the “Lucas” object.

So, could we alter or transform the object? Nope, but just a new String object (Lucas object) was generated, and the “name” variable now points to that object. This illustrates why you can impact the value of the “name” variable. This implies that a Java String is immutable!

Just a refresher, the objects in the heap have separate memory addresses.

Let’s look at why Java Strings are immutable with my other content.

--

--

Harshana Samarasinghe
CodeX
Writer for

“Truth can only be found in one place: the code.” - Associate Engineer — Java Technology at Virtusa Sri Lanka -