Could anyone please tell me what is the meaning of the following line in context of Java:
final variable can still be manipulated unless it's immutable
As far as I know, by declaring any variable as final, you can't change it again, then what they mean with the word immutable in above line?
If you have a final reference to a Java object you can still manipulate it but cannot change its reference. For instance this code is perfectly legal:
But you can't say:
After the first assignment to l. Note that you can do this though:
This can be done because when l is declared it is not assigned to anything not even null. So you are allowed to assign something to it one time only.
Same thing goes for primitives. You can assign a value to it like this:
But now you cannot manipulate it further since the only thing you can do to primitive types is to assign values to them.
Yes the final variable can be modified.
You can't change the reference but the fields of the the object can be modified. for more details
You can manipulate mutable final variables for e.g. of type StringBuffer but you cannot manipulate final variables of immutable types.
In case of mutable variables, new object is not created every time it's value is changed. But in case of of immutable types, whenever you change value, new object is created, so when you make it final, you cannot modify it.
It means that if your final variable is a reference type (i.e. not a primitive like int), then it's only the reference that cannot be changed. It cannot be made to refer to a different object, but the fields of the object it refers to can still be changed, if the class allows it. For example:
The content of the StringBuffer can still be changed arbitrarily:
But you cannot say:
or
On the other hand:
Strings are immutable - there simply isn't any method that would enable you to change a String (unless you use Reflection - and go to hell).
The one that always kills me?
If you want final variables to actually be as safe as you thought they were, you need a lot of extra code to return a copy of a String[].
You can call any method on it even if the method can change the state of the object the reference is pointing to. E.g
This is fine because
myClass
itself is not changing, i.e you are not doingmyClass = myClass1;
.