> What actually is behind the scenes?
The java compailer uses String in order to parse the source code you write.
For that reason, String is both final and immutable in order to avoid someone reimplementing String (what will cause the javac to be unable to properly compile the code) and to avoid unexpected changes to a string while it's being processed by the compiler.
hope that helps,
kotsss
> The java compailer uses String in order to parse the
> source code you write.
> For that reason, String is both final and immutable
I'm not entirely sure why, but I know that it's not because of that. It's most likely a combination of efficiency and simplicity. Strings are used a lot, and certain optimizations can be applied if we know they're immutable. Your code is also simpler if you know that a String you're passing around won't be moified.
One of the arguments was that while checking a FilePermission, another thread could change the String referring to the filename whose permissions are being checked, so the check will wrongly pass or fail. So if the check can't be securely implemented, the mutability can't be securely implemented.
It also makes possible the complete equivalence of Strings and quoted strings in the Java language. Without immutable Strings, you would have to have C++'s const &string construct: otherwise you could corrupt quoted strings by passing them to any method that didn't know whether they were Strings or quoted strings.
It also makes better string pooling possible.
The argument above from javac doesn't hold water. The compiler uses hundreds of JDK classes which are mutable.
Java took much of its inspiration from all of Smalltalk, Modula-3, Objective-C, and as much C++ as necessary but no more, so that inference doesn't follow at all.
Immutability of Strings fundamentally flows from the semantic identity of Strings and quoted strings. The security information story above came from Ken Arnold.