Why Are Java Strings Immutable?

24 Jan 2025

One common answer to the question why are Java strings immutable? can be sumed up in one word: security.

Unfortunately, attempts to expand on this often become vague and hand-wavy extremely quickly. Not to pick on anyone in particular, but this is a paraphrase of a not uncommon explanation:

The String type is widely used to refer to specific network connection, file names, etc. If String was mutable, a connection or file could easily be changed and lead to serious security threats.

That’s it. That’s the explanation. To me, it does not explain anything - it just begs more questions of the but how exactly? variety.

It also appears to contradict other arguments commonly made which state that passwords in Java should be handled as character arrays - not as strings - for security! (Because strings cannot be nulled out in the same way that char arrays can be - and can hang around in the JVM heap longer before being garbage collected. But then a bad actor still needs to be able to dump the JVM to access that data… So if they can do that you probably have bigger problems, anyway…).


James Gosling (the founding father of Java) gave an interview in 2001 in which he touched on string immutability:

One of the things that forced Strings to be immutable was security. You have a file open method. You pass a String to it. And then it’s doing all kind of authentication checks before it gets around to doing the OS call. If you manage to do something that effectively mutated the String, after the security check and before the OS call, then boom, you’re in. But Strings are immutable, so that kind of attack doesn’t work. That precise example is what really demanded that Strings be immutable.

Well, that at least does walk through a threat scenario in more detail, but it is still a bit high level for me to truly grasp “boom, you’re in” (this was, to be fair, only one small part of a wide-ranging interview).

I take the point, however. If you can fool the security mechanism into thinking it’s OK to give you access to a harmless file in a public directory, then maybe you can then immediately mutate the file location details to point to a restricted file you should not be able to access… And, yes, immutable strings do mitigate this type of threat.


You can do lots of clearly useful things with immutable objects in general - such as using them with confidence as keys in maps; cacheing them, and so on. And that includes strings - for example, as used by the JVM’s “string literals” pool. But that is not related to security per se. Don’t trust hand-wavy arguments.