Search code examples
javaoopmemoryfinal

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


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?


Solution

  • 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