Where is the local final variable in the saved method (Stack / Heap)?

I know that method variables are stored on the memory stack, but are slightly confused with final . I looked through many links, such as this one could not get the correct understanding? below is an example of an inner class in which final variables are available, and non-final local variables are not the same as they are stored on stack

 class Employee { public void getAddress(){ final int location = 13; int notFinalVar = 13; class Address { System.out.println (location); System.out.println (notFinalVar); // compiler error } } 

Update : Now itโ€™s become known about the hidden fields of the synthetic field ( inner class heap memory area ) in which a copy of the final variables is stored, so does this finally mean that the final variables are stored at the end of the Stack memory Area ?

+7
java oop memory final
source share
1 answer

After reading some SO answers and articles, I understand:

The answer is a stack . The entire local variable (final or absent) is stored on the stack and leaves the scope when the method completes.

But about the final variable, the JVMs take them as a constant since they will not change after launch. And when the inner class tries to access them, the compiler will create a copy of this variable (the wrong variable it self) in the heap and create a synthetic field inside the inner class, so even when the method completes, it is available because the inner class has its own copy.

so does it finally means that final variables are stored in finally Stack memory Area?

the final variable is also stored on the stack, but a copy of this variable, which the inner class stores on the heap.


a synthetic field that does not actually exist in the source code, but the compiler creates these fields in some inner classes to make this field available. In a simple hidden field.

References:

How to mark a variable as final to allow inner classes to access them?

You cannot reference a non-finite variable inside an inner class defined in another way

Secrecy of accessibility in local inner classes

+12
source share

All Articles