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 local variable question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "final local variable question" Watch "final local variable question" New topic
Author

final local variable question

Erap Estrada
Ranch Hand

Joined: Nov 08, 2006
Posts: 92
I want to know the logic why the variable "ai" from the code below is not visible to the inner class "Inner". Thanks!



SCJP with 98% by...
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Method local classes can only access local variables that are declared final.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

An instance of a local class could still be reachable after the method exits and its local variables are destroyed. If local variables are final, then their values can be copied into the instance.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381
Really can not understand this..
If local variables are final, then their values can be copied into the instance.

Means if the varibale is non final wont be its value be copied into instances?Will the final variable wont lost after the method finises?May be this question sounds silly ... please help!


~Sanjeev Singh<br />SCJP 1.5
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

It might not be obvious how an instance of a local class could still be reachable after the method exits. The key is in upcasting the reference to a type that exists outside the method's scope, as illustrated here...
Kalpesh Jain
Ranch Hand

Joined: May 29, 2006
Posts: 30
The invoked methods(and their variables) goes on to the call stack.Classes once loaded, resides on the heap. Method local classes are no exception to this. Method variables survive till method itself is alive after which they are flushed from the stack. But local classes may still have their reference with other variables hence they cannot be destroyed. And thats the reason why local classes can only access final method variables so that the method lives or dies final var's value will always be the same. If at all local classes were holding non-final variables, and if anybody tries to change its value, jvm will throw exceptions as method may not be alive.


Its a j a v a
 
 
subject: final local variable question