• 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' local variables

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm studying the SCJP 1.5 book by Kathy Sierra and Bert Bates, and have the following question (related to pages 645 and 646):

Why can 'final' local variables be referenced in a method-local inner class? That is, what impact does the 'final' modifier have on the variable's lifecycle/scope or garbage collection?

Example (from book) where variable z must be 'final':

 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

Let us know if this thread answers the question.
 
Cindy Rogers
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, thanks!

Cindy Rogers
 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
method vars exist on stack, instance vars exist on heap. Since method local class instances or anonymous instances may be passed out of the method as part of a return value, they are required to exist after the lifetime of the method. The compiler accomplishes this by copy them from stack to heap. How you have a copy of the var on the heap this extends lifetime of the variable beyond the method scope. This stack->heap copy process is only done for final variables so they can exist outside of their method scope.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic