You will get the answer of your question if you think about the consequences of method local inner class using variables of the same method. Local variables of the method exists only for the lifetime of the method. When the method ends, the stack and the variable is also destroyed. But even after the method completes, the inner class object created within it might still be alive on the heap. And if this object tries to access a variable which is no more then!!!
Joined: Jun 03, 2008
very thank you for your reply. OK ,then where are the FINAL variables stored?.is it heap?.
Because the variable is final, the inner class instance keeps a copy of that variable's value - either primitive, or the reference to an object. If the variable was a reference to an object, this object will still have at least one reference (in the inner class) and not be garbage collected.
So yes, in the end, its value is stored on the heap, within the instance. [ August 19, 2008: Message edited by: Rob Prime ]
Since JDK 6, you can't always be sure that objects will be stored on the heap. Sometimes, if the JVM can determine that an object is only accessible from within a single thread, and it can determine when the last variable referencing that thread has gone out of scope, it can allocate the memory for the object on the stack rather than the heap. This means it can be garbage collected very efficiently. It also means the JVM can ignore synchronization requests if it's already determined that no other threads can touch the object. This is useful for a class like StringBuffer, whose methods are synchronized but in most cases this is completely unnecessary.
Anyway, the point here is that nowadays it's often hard to know for sure whether an object is really on the heap, or on the stack. And it generally makes very little difference, from the programmer's perspective.