Search code examples
javamemorymethodsheap-memoryactivation-record

Trying to increment local variable from a separate method but not working. Confusion about Activation Stack/Record


public class Demo {
    public static void main(String[] args){
        Demo instance = new Demo();
        instance.init();
    }
    public void init() {
        int size = 0;
        inc(size);
        System.out.println(size);
    }
    public int inc(int size){
        size++;
        return size;
    }
}

When I call the code above, the number zero is returned.

Even declaring size as a class attribute instead of a local variable does not solve the problem. I understand that when a method is complete, the corresponding record (containing local variable and such) is popped off of the activation stack. But, if the size variable is declared in the init() method, and then incremented and returned in a separate method (inc()), shouldn't size be equal to 1?


Solution

  • When incrementing you do not assign the value to anything, it increments it, but it does not store it anywhere so the value remains 0, try doing like this.

    public class Demo 
    {
        public static void main(String[] args)
        {
            Demo instance = new Demo();
            instance.init();
        }
        public void init() 
        {
            int size = 0;
            size = inc(size);
            System.out.println(size);
        }
        public int inc(int size)
        {
            size++;
            return size;
        }
    }
    

    or like this

    public class Demo 
    {
        public static void main(String[] args)
        {
            Demo instance = new Demo();
            instance.init();
        }
        public void init() 
        {
            int size = 0;
            System.out.println(inc(size));
        }
        public int inc(int size)
        {
            size++;
            return size;
        }
    }