The API for string suggests another good reason for strings to be immutable. Since they are immutable, they can be shared (this is basically exactly what I was talking about with the jvm string pool, but has a different consequence).
So, we say that as String is "thread-safe". That means that we can use it on more than one
thread without worrying about what is happening to it on another thread.
For example, let us consider a c-style string, for a minute. In c, we know that we need to have \0 at the end of every string, so that we know where the end of the string is.
So lets say we have the string "Hello". On one thread, we decide to append " World" to it. So we start by writing the space (code 32) in index 5, and 'W' in index 6, etc.
Now lets say that after we've put the W in position 6, but before we put the o in position 7, a DIFFERENT thread decides to read the string. But now, the string has no \0 ANYWHERE. So it has no end.
We say that the string is in an inconsistent state, and this is very important in multithreaded programming.
Now, lets say that we cannot modify a string after its been created. Then it can NEVER be in an inconsistent state, so we know that it is thread safe.
This is a very good reason for a String to be immutable.
- Adam