• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

final variable lives on?

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Allen

You can check this using inner class.as follows.


i hope it will help you
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic