Java String immutability and intern method.

All of you would be knowing the fact that String is immutable in java, which means once constructed can not be altered. This allows the jvm to have a literal pool, literal pool will be helpful to reduce the memory usage and to increase the performance. Each time when a String is created JVM check the literal pool, if the literal is already available the same reference would be returned. If not a new String object will created and added in the literal pool.

The above mentioned rules are applicable only when you create a String like a primitive or a literal/constant. (String str = “India”). But when you create a new String object (String str = new String(“India”)) the above mentioned rules are overridden and a new instance is created always.

But the intern API in the String class can be used to pick the String reference from the literal pool even though you create a String using new operator. Please check the below given example. Although the str3 is created using new operator since we used the intern method JVM picked up the reference from the literal pool.

Console Output.

One thought on “Java String immutability and intern method.

Leave a comment

Your email address will not be published. Required fields are marked *