Java Notes — Immutable Strings

Ekin Gün Öncü
2 min readFeb 21, 2022

--

String objects are immutable means that we are not allowed to change them because all attributes of the String object are defined as final. But we can redefine the values of String variables because when we redefine a String variable’s value with another string literal java doesn’t change or remove the value from the memory but creates a new value and points the variable to that value placed in memory a place called String Pool or String Constant Pool.

Likewise, if we create a variable with a string literal previously defined instead of creating a new value in memory our variable java will point to the older one.

It enables java to save a ton of memory space. This behavior is valid unless the string variable is created using the new keyword.

Or if we call the intern() method of String even after creating the object using the new keyword it will point the value from String Pool if any value exists with the String same literal.

Therefore Strings are immutable because;

String Constant Pool feature aims to make Java consume less memory. Therefore it makes sense not to create a new object each time when we want to use the very same literal. But if String objects would be mutable it would impact another variable that points to the same String object.

--

--

Ekin Gün Öncü
Ekin Gün Öncü

Written by Ekin Gün Öncü

I am an enthusiastic and experienced software developer who keeps learning every day.

No responses yet