GeeCON Prague 2014*
The moose likes Java in General and the fly likes can final variables be altered? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "can final variables be altered?" Watch "can final variables be altered?" New topic
Author

can final variables be altered?

Suresh Ramanan
Greenhorn

Joined: Feb 08, 2009
Posts: 27
Hi!

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?

Suresh


SCJP 5.0 SCWCD 1.5 SCWCD Hall of Fame
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

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.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3016
    
  10
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.
Suresh Ramanan
Greenhorn

Joined: Feb 08, 2009
Posts: 27
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.
Thanks again
 
GeeCON Prague 2014
 
subject: can final variables be altered?