why can't a method inner object use the local variables of that method unless those are declared FINAL.can any body explain in detail.thanks in advance
thanks and regards<br />Santhi Bharath<br />SCJP 5.0, SCWCD 5.0
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!!!
Santhi Bharath
Ranch Hand
Joined: Jun 03, 2008
Posts: 75
posted
0
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.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.