This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Local final variables and method local inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Local final variables and method local inner class" Watch "Local final variables and method local inner class" New topic

Local final variables and method local inner class

Jolly Tiwari
Ranch Hand

Joined: Mar 26, 2006
Posts: 77
HI! all,
i am stating a passage from inner classes in K&B book

"The local variables of the method live on the stack, and exist only for the lifetime of the method.
You already know that the scope of a local variable is limited to the method the variable is declared in. When the method ends, the stack frame is blown away and the variable is history.
But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable. Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them. Unless the local variables are marked final!"

Can any body please tell me How method local final variables will be retained and accessed as according to me they also reside on the stack .still inner class access them and works correctly.



[BPS: Removed shouting from the subject line]
[ May 21, 2008: Message edited by: Ben Souther ]
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

Typing with the caps-lock button down in a web forum is the same as shouting.
Please don't shout.


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Stevi Deter
Ranch Hand

Joined: Mar 22, 2008
Posts: 265


To copy from an answer I gave to a similar question here:

The compiler gives the local class access to the variables by automatically creating a private instance field to hold a copy of the variable, as well as creating hidden parameters in the constructor to automatically initialize those private instances.

This can only work if the variables to be copied are final, so that the local class can be guaranteed that its local values are the same as the instantiating scope.

There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
I agree. Here's the link:
subject: Local final variables and method local inner class
jQuery in Action, 3rd edition