Java : Immutable Strings

Posted in Java Strings By Raj On December 24, 2017


In Java, the strings are immutable which means once you create a String object you can not change it, if you want to know why strings are immutable then first you must know What is String Constant Pool

What happens when you create a string in Java, the JVM creates an object into the string constant pool, if you create another string, first the JVM looks for string object in the string constant pool, if it exists then it will return the reference of existing string object otherwise it will create a new object and return its reference if you make string mutable then if you change one string object then it will impact on all other string objects so the String’s are immutable



If you run the below code, you will see the same “Hello” output, because the string is immutable and we cannot change it, but internally a new object is created without having any reference 

Example: String Immutable

Output :

You need to assign newly created object to the String variable something like below