• Post Reply Bookmark Topic Watch Topic
  • New Topic

where does a local variable marked final live?  RSS feed

 
Q Drini
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was reading about local inner classes, on page 645/646 of the SCJP book by K.S and B.B., and it says that a method-local inner class can access a local variable of the method the inner class is in only if it's marked final.
Does this mean they live on the heap?

Thank you in advance.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, they live on the stack*, like other local variables. When an inner class needs to access a local final variable, what actually happens is that the value of the variable is copied from the stack to the heap when the class is instantiated. The reason the local variable needs to be final is to avoid confusion if the programmer tries to modify the local variable without realizing that the inner class has a copy, which will be unaffected. Forcing the programmer to declare the variable as final prevents this.

An exception to "they live on the stack" is if a local final variable is initialized with a compile-time constant, then that variable is also a compile-time constant, and may not exist at all as a variable on the stack. Instead the compiler will generally put its literal value in the bytecode directly, the same as if you had used a literal in the first place rather than a variable. That has nothing to do with inner classes though.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!