• Post Reply Bookmark Topic Watch Topic
  • New Topic

final variable and local variable  RSS feed

 
Santana Iyer
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Inside my method local inner class

class SomeClass
{
void someMethod()
{
final int i; // accessible to Method local inner class
int j; // not accessible

class MethodLocalInner
{
// here i is accessible but not j
}
new MethodLocalInner();
}
}


now reason given is that you can pass methodlocalinner class reference
to outside method but at that time stack frame may be popped for that method so access to method local variable not allowed inside method local inner class than why access to final variable allowed
Is it that final local variable are stored in different memory or ?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler creates a synthetic field in the inner class, and copies the value of the local variable to it. That can only savely be done when the local variable is final, because then we can be sure that its value won't change, so the copy can't get out of sync.
 
Santana Iyer
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for reply,
if possible kindly put some more light (can you please elaborate)
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You asked if final variables are stored differently in memory. Ilja said no, they're not; the difference is that since a final variable never changes, Java can secretly make a copy of the final variable and store it in the local class object. This makes it look as though the local class can access the final local variable, but really, it only accesses that copy which is made at the moment the object is constructed.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Ernest said.

Imagine the same would work with a non-final variable. Now you could change the value of the local variable after the local class object got instanciated and the copy created. But if you do that, the field in the local class object doesn't get updated - suddenly the method and the local class object do see different values; the illusion is destroyed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!