I know that Strings are immutable.
Then, what is the difference between:
String name ="Name";
final String name ="Name";
Why do we use final in this context? Because String is already immutable there seems to be no need. Second related question, why are String’s immutable?. Other Data Types like int, boolean are not. If String is immutable does that make it thread-safe? I read that “if String been mutable, a request to load “java.io.Writer” could have been changed to load “mil.vogoon.DiskErasingWriter”” means ?
There are a lot of questions here, but here are a few notes that should answer most of them:
finalmeans the variable can be assigned only once. It has nothing to do with mutability, which is a property of the object, rather than the variable (which is simply a handle)Stringis immutable, because you can’t change its internal state (it has aprivate char[] charsthat hold the characters). Primitives are also immutable. This is better visible in their wrapper equivalents –Integer,Longetc.