In general, it’s easier to write and view sensitive code when the values do not change, because there are fewer movement operations that can affect the result.
Imagine a code like
void doSomethingImportant(String name) { if (!isAlphaNumeric(name)) { throw new IllegalArgumentException(); } Object o = lookupThingy(name); // No chance of SQL-Injection because name is alpha-numeric. connection.executeStatement("INSERT INTO MyTable (column) VALUES ('" + name + "')"); }
The code performs some checks to prevent escalation of privileges, but this is only done if isAlphaNumeric(name) is true when the executeStatement argument is executeStatement .
If the first two statements were reordered, this would not be a problem, so the uncertainty arises in part due to poor alternation. But other code may call this function and assume that name does not change it, so you may need to run and re-run validation checks.
If String not immutable, it could be changed to lookupThingy . To make sure that the security check works, there is a much larger amount of code that must be correctly executed to ensure that this code is safe from SQL injection.
Not only the amount of code that must be executed correctly, but also the supporting one, which makes local changes to one function, can affect the safety of other functions far. Nonlocal effects make code maintenance difficult. Maintaining security features is always dangerous, since security vulnerabilities are rarely obvious, so variability can lead to poor security over time.
Why is this the reason the string is meant to be immutable?
This is separated from why it is poorly secure.
It is widely believed that programs written in languages with easily accessible immutable string types make fewer unnecessary copies of the buffer than those that do not. Unnecessary copies of the buffer destroy memory, cause GC to be rejected, and can lead to simple operations with large inputs much worse than with small inputs.
It is also widely believed that using immutable lines makes it easier to write the right programs, because you are unlikely to be able to protect the archive.