Scope of global variables in a java class and their behavior in methods of the same class

I am new to programming and Java and I have some confusion regarding the behavior of global variables in methods of the same class. In an exercise question provided by the course I am taking, I am asked what is the value of variable b after executing inc(b).

    int b;
    int inc(int b){
        b++;
        return b;
    }
    b = 5;
    inc(b);

The answer is 5, rather than 6, which I understand is because Java is pass by value and all the arguments in the method inc is simply forgotten afterwards.

On the other hand, in a java class it is recommended to write set and get methods for all the instance variables. Then my question is, why is the setter able to change the instance variable and maintain its value outside the setter? In other words, why is the variable change "forgotten" in the above example, but "remembered" in a set method?

    public void setName ( String n ) {
        name = n;
    } 
Jon Skeet
people
quotationmark

In other words, why is the variable change "forgotten" in the above example, but "remembered" in a set method?

In your inc method, you're not changing the field called b at all. You've got a parameter called b, so every time the code refers to b within the method, it refers to the parameter instead of the field. This is called shadowing. If you change it to:

int b;
int inc(int b) {
    this.b++;
    return this.b;
}

... then the parameter will be ignored, and it will increment the field instead.

Basically, you need to think about what you want the inc method to do:

  • Is it meant to increment its parameter and return the new value? If so, it might as well be static - it doesn't interact with any state of the instance
  • Is it meant to increment the field and return the new value? If so, it should be parameterless - it's not using the parameter.
  • Is it meant to set the field to the parameter value and then increment it? If so, I would strongly advise a change in design (I know this is only an example) and definitely a change in parameter name.

people

See more on this question at Stackoverflow