I know this is kind of crazy but i read somewhere in Head First Servlets and Jsps that even final variables can be manipulated unless its immutable. (Page 204, Q 4).
Can someone please throw some light on this?
Final variables cannot be changed. But perhaps you are confusing a variable with an object which it might contain a reference to. You cannot change a final variable to refer to a different object, but you can certainly change the state of the object which a final variable refers to. Unless, as you observe, the object is immutable.
I suspect that Paul is correct, in that what HFJ was most likely talking about was the fact that a final variable doesn't prevent anyone from changing the object that variable refers to - if that object is mutable. This is a basic and important point in understanding the distinction between a final variable and an immutable object. Or more generally, between a reference, and the object it refers to.
However, beyond that, it's also true that final variables are not as immutable as we like to think. Final variables can and do change their values under two different cases I know of:
1. Using reflection. This is well-known, I think - reflection breaks many "rules" of Java.
2. Using helper methods in a constructor. Java guarantees that by the end of the constructor, the method may have one and only one value. And it may only be explicitly set once. But it's possible, during the execution of the constructor, to observe a "final" variable changing from its default value to an explicitly-set value:
The same effect can also be observed using a static final variable, a class initializer, and a static helper method. Same idea; nothing really new there.
Joined: Feb 08, 2009
hey thanks a lot for the replies..
So am i right when i say, a final variable, if its a reference to an object can only point to that object and no other?
And if anything can be changed at all, its the state of the object unless immutable.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com