Java works withs "Call by Value concept". If its stack and heap is visualized then java tries to find the values of any variable in local workspace, if its not found in local then it tries to find out in object which is in heap.
Example
class Foo { int x; public void call(int x) { x++; } public static void main(String[] args) { Foo foo = new Foo(); foo.x = 5; System.out.println(foo.x); foo.call(foo.x); System.out.println(foo.x); } }
Output of above program would be : 5 , 5 Desciption : In main method, value of x is assigned 5 on reference of "foo: In call method, there is local variable named "x"(passed as argument) in workspace. so it's value would be changed in its workspace only. when control from this function returns to main method. In main's workspace value of "x" is still 5.
Example
class Foo { int x; public void call(int y) { x++; } public static void main(String[] args) { Foo foo = new Foo(); foo.x = 5; System.out.println(foo.x); foo.call(foo.x); System.out.println(foo.x); } }
Output of above program would be : 5 , 6
Desciption : In main method, value of x is assigned 5 on reference of "foo: In call method, there is no local variable named "x"(passed as argument) in workspace. So java finds it in reference through which "call" function was called and value of "x" is there 5, call method increments its value to "6" so it's value would be changed reference i.e. "foo". when control from this function returns to main method. Now In main's workspace value of "x" is 6 because here we printed "x" on foo reference.
I hope this would help you to clear your concepts.
Regards, Sushil Jain