A method can have final and non-final variables in java. 1.Where these(final&non-final) variables are stored in JVM? 2.what is the life time of final variables of a method? 3.Can we access final variables of a method out side of that method, if so how? Give me example and detailed explanation.
Hey guys last two questions really don't fit for this category(SCJP) but the first one is really nice and it would be nice if you guys please explain "how JVM treats (regarding storing in memory etc..) final and non-final variables(local or instance).
Originally posted by Shiva Shankar: if the final variables are also stored in stack,how can method local inner classes access only final variables of that method,why not non-final variables?
The problem is that the life time of the local variable might be shorter than that of the instance of the inner class. The compiler uses a trick to create the illusion of accessing the local variable even after its lifetime is over - it copies its value to a synthetic field of the inner class when it is instanciated. The local variable needs to be final to make sure that its value cannot get inconsistent with the copy in the synthetic field.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Dec 07, 2006
what is synthetic field (of the inner class)?
Joined: Jul 11, 2001
Originally posted by Shiva Shankar: what is synthetic field (of the inner class)?
A synthetic field is a field that is introduced by the compiler and only exists in the byte code, not in the source code. I think there even is a synthetic flag in the byte code that is set for those fields, but I'm not sure about the details.
Synthetic members are necessary because at the byte code level, there are only top level classes - the JVM doesn't know about inner, nested or anonymous classes. The compiler has to use some tricks to implement the special access rules that apply to those concepts at the source code level.