Search This Blog

Tuesday, August 01, 2006

Why String class is immutable?

JVM internally maintains the "String Pool". To achive the memoryefficiency, JVM will refer the String object from pool. It will notcreate the new String objects. So, whenevr you create a new stringliteral, JVM will check in the pool whether it already exists or not.If already present in the pool, just give the reference to the sameobject or create the new object in the pool. There will be manyreferences point to the same String objects, if someone changes thevalue, it will affect all the references. So, sun decided to make itimmutable.

2 comments:

Kocka said...

+ some security reasons I think :)

nice blog anyway, I will add it to my links

Anonymous said...

Here are few more reason for string immutability.

http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html