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?

2

There are 2 best solutions below

2
On BEST ANSWER

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;
    }
}
0
On
size = inc(size);

will solve your problem, since you are not using a public scoped variable.

If you want to make this a bit elegant (at least I think this will be a bit more handy), then you need to declare a variable as a class variable. I will illustrate this to you:

public class Demo {    
  int size; //global range variable

  public static void main(String[] args){
    Demo instance = new Demo();
    instance.init();
  }

  public void init() {
    this.size = 0;
    inc();
    System.out.println(this.size);
 }

 public void inc(){
   this.size++; //will increment your variable evertime you call it
 }
}