File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes final question... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "final question..." Watch "final question..." New topic

final question...

Krep Lock
Ranch Hand

Joined: Sep 19, 2006
Posts: 43
no, this isn't the last question i'll be asking, it's a question about the final keyword. the following code snippet stumped me:

i was sure that final locks in a variable's value, but in this program label gets updated every time you click a button.

my guess is that final only locks the reference to the label object, so updating the object itself is fine. but why bother to final the reference in this simple situation?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Without seeing more code, it's impossible to say whether "final" is actually doing anything useful. Some people like to use it liberally just to make it clear which variables change and which ones don't, and there's this whole thing with anonymous inner classes which requires the use of local final variables; that one comes up a lot in GUI work, so it might be that.

But in any case, yes: final has no effect at all on an object that a final variable is pointing to; it only affects the variable itself.

[Jess in Action][AskingGoodQuestions]
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi all,

Krep wrote:
my guess is that final only locks the reference

Good guess. Marking a primitive variable final means, that it's value has to be assigned once and for all. It cannot be changed afterwards.
Marking an object variable final means, that it cannot be reassigned to another variable. But the object the variable is pointing to may be changed.
See example:

And as Ernest already mentioned: "this whole thing with anonymous inner classes".
A method local inner class can only refer to local variables if they are final.
See second example:

The depicted line will only compile, if variable year is final.
And that may be the cause why your JButton is marked final, as in GUI codes anonymous inner classes are frequently used e.g. for action listeners.


all events occur in real time
I agree. Here's the link:
subject: final question...
It's not a secret anymore!