File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes final variable lives on? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "final variable lives on?" Watch "final variable lives on?" New topic
Author

final variable lives on?

Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
I came across a chapter review question as follows:

Q. Variables declared inside a method as final retain their value between invocations of the method in which they are defined (true/false).

A. The answer to this question is true (at least in Java 1.2)

I tried to build a method which I could prove this to be true but could not. Is there anyone who has an example which can prove this concept? Although I can understand that a final variable would be considered a constant, it goes against my understanding of variable scope being limited to the method in which it is declared.
Sundar Murthi
Ranch Hand

Joined: Mar 05, 2004
Posts: 209
Hi Allen

You can check this using inner class.as follows.


i hope it will help you
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Chris,

I'm not sure I follow everything that's going on here. Perhaps I'm misunderstanding the question or the answer. From what you've said, I came up with this little test program:



From what you've said, I'd expect this to print 1 and 1, but it doesn't, it prints 1 and 2 (which is what I'd expect, frankly). Was there any explanation given for that answer that we might investigate further?


SCJP Tipline, etc.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12671
    
    5
Each call to your doIt method gets a new final int x.
A special meaning of final for variables declared inside a method was added to support inner classes so that if the inner class object lives on past the method call, the variable will still exist.
Bill


Java Resources at www.wbrogden.com
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: final variable lives on?
 
Similar Threads
Method overriding
Dan's Mock: Field declaration Q 7
why 'method local inner class' can only access final variable?
What does it means?
Final method