Possible Duplicate:
String and Final
From http://docs.oracle.com/javase/6/docs/api/java/lang/String.html I can read that:
Strings are constant; their values cannot be changed after they are created.
Does this mean that a final String
does not really make sense in Java, in the sense that the final
attribute is somehow redundant?
The string is immutable means that we cannot change the object itself, but we can change the reference to the object. The string is made final to not allow others to extend it and destroy its immutability.
The String is immutable in Java because of the security, synchronization and concurrency, caching, and class loading. The reason of making string final is to destroy the immutability and to not allow others to extend it. The String objects are cached in the String pool, and it makes the String immutable.
In Java, we know that String objects are immutable means we can't change anything to the existing String objects. final means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g).
If a variable is marked as final then the value of that variable cannot be changed i.e final keyword when used with a variable makes it a constant. And if you try to change the value of that variable during the course of your program the compiler will give you an error.
The String
object is immutable but what it is is actually a reference to a String
object which could be changed.
For example:
String someString = "Lala";
You can reassign the value held by this variable (to make it reference a different string):
someString = "asdf";
However, with this:
final String someString = "Lala";
Then the above reassignment would not be possible and would result in a compile-time error.
final
refers to the variable, not the object, so yes, it make sense.
e.g.
final String s = "s"; s = "a"; // illegal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With