I know that method variables are stored on stack of the memory but slightly confused over final
. I had browsed many links like this could not get proper understanding? below is the example of inner class
in which final
variables are accessed and local non-final
variables are not as they are stored in 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: Just now came to know about hidden fields called synthetic field
( inner class heap memory area
) in which copy of final variables are stored so does it finally means that final variables are stored in finally Stack memory Area
?
Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
The stack is used for dynamic memory allocation, and local variables are stored at the top of the stack in a stack frame. A frame pointer is used to refer to local variables in the stack frame.
The heap is a memory used by programming languages to store global variables. By default, all global variable are stored in heap memory space.
Stack in java is a section of memory which contains methods, local variables, and reference variables. Stack memory is always referenced in Last-In-First-Out order. Local variables are created in the stack.
Reading through some answers of SO and articles, My understanding is :
The answer is stack. All local variable (final or not) stored into the stack and go out of scope when the method execution is over.
But about final variable JVM take these as a constant as they will not change after initiated . And when a inner class try to access them compiler create a copy of that variable (not that variable it self) into the heap and create a synthetic field inside the inner class so even when the method execution is over it is accessible because the inner class has it own copy.
so does it finally means that final variables are stored in finally Stack memory Area?
final variable also stored in stack but the copy that variable which a inner class have stored in heap.
synthetic field are filed which actually doesn't exist in the source code but compiler create those fields in some inner classes to make those field accessible. In simple word hidden field.
References :
How does marking a variable as final allow inner classes to access them?
Cannot refer to a non-final variable inside an inner class defined in a different method
Mystery of Accessibility in Local Inner Classes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With