• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final automatic variables

 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If we want to use a local variable inside a local class or anonymous local class - we have to mark it final.
But what does that keyword mean? It means that the reference can not be reassign. But how does it affect the scope of the variable? Why can we use final variables inside a local class?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Final variables are not only prevented from reassignment, they also don't live on the stack like other local variables, but are stored on the heap, which makes them also accessible for inner or anonymous classes.

Also check this thread:

http://www.coderanch.com/t/407046/Java-General-beginner/java/where-final-static-variable-stored
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sebastian Janisch wrote:Final variables are ... stored on the heap, which makes them also accessible for inner or anonymous classes.[/url]


Where final variables are stored is not the reason for them being accessible to local inner and anonymous classes. If you read the thread which you gave link to, Henry has written

Henry Wong wrote:A final local variable is a special case, not because the scope of the local variable is different -- but because since it can't change, the compiler generated code for the inner class to have a copy of the variable. (At instantiation time, when both are in scope)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic