From : http://sureshk37.wordpress.com/2007/12/18/why-string-is-immutable/
String in a class it is used to holding the array of characters. The difference between String and StringBuffer is String is immutable where as StringBuffer is mutable. Means we can not change the value of the string.
Why it so?
Actually in java, Strings are handling in Pool format.
For example:
String str1 = “xyz”;
This string(str1) will be stored into memory in particular address. When we defining new String with same array of characters like
String str2 = “xyz”;
Now JVM will check in String Pool where there is same characters are available or not. If two Strings are match the JVM will refer str1 address to str2. Now the str1 and str2 referring the same characters in same memory location. This is a good idea for increasing memory efficiency.
When we change the str1 characters, the changes will be reflected to str2. Because both str1 and str2 variables are referring the same memory location. For avoiding this we are keeping String as immutable. However we can use StringBuffer if you want to do modifications in the string.
From:http://www.velocityreviews.com/forums/t146183-why-string-is-immutable.html
Java has this thing called a SecurityManager, and it is responsible for checking that
unprivileged code (for example, an applet) is allowed to do stuff. To
pick one example, applets are typically allowed to contact their server
of origin with sockets, but not other servers. So let's say I write
this:
String hostName = "my.origin.server.com";
Socket s = new Socket(hostName, 1234);
Looks fine. In the second line, the SecurityManager will first check to
be sure that "my.origin.server.com" really is the origin server. Then
it will establish a connection to that server. But this only works if
the server name can't change between the security check and establishing
the connection. If String were not immutable, I could do this:
String fakeHostName = "my.origin.server.com";
String realHostName = "evil.server.com";
String hostName = new String(fakeHostName);
new Thread() {
public void run()
{
while (true)
{
hostName.mutateTo(realHostName);
hostName.mutateTo(fakeHostName);
}
}
}.start();
boolean success = false;
while (!success)
{
try
{
Socket s = new Socket(hostName, 1234);
// try talking to evil.server.com
success = true;
}
catch (SecurityException e) { }
}
It might take a while, but eventually, a context switch would happen
between the security check and establishing the connection. When that
happens, security is compromised.
See how that works? It's not impossible to code around, but if String
were mutable it would be a lot bigger pain to write methods that make
proper use of java.security.AccessController.doPrivileged.