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?
References are final, Objects are not. You can define a mutable object as final and change state of it. What final ensures is that the reference you are using cannot ever point to another object again.
final
refers to the variable, not the object, so yes, it make sense.e.g.
The
String
object is immutable but what it is is actually a reference to aString
object which could be changed.For example:
You can reassign the value held by this variable (to make it reference a different string):
However, with this:
Then the above reassignment would not be possible and would result in a compile-time error.
It makes sense. The
final
keyword prevents future assignments to the variable. The following would be an error in java: