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;
}