Search code examples
javaheap-memoryactivation-record

would the variable 'x' in this piece of code be stores in stack memory, heap memory, or both?


So regarding the variable int x. At the beginning of this class, int x and and String s are stored in heap memory. However, when the constructor is initiated, is int x stored in stack memory AND heap memory since the constructor is technically a method or not?

public class A {
    int x;
    public String s = "";

    public A(int y) {
        x = y;
    }
}

Solution

  • y is stored on the stack as it is a scoped variable to that method. x is just modified in-place on the heap.