java - Unable to understand the issue "call By Reference" -
this question has answer here:
in java, object reference used call reference , variables used call value.
here’s example:
class foo{ int x; int y; } public class callbyref { public static void main(string[] args) { foo foo = new foo(); foo.x=5; foo.y=10; system.out.println(foo.x+", "+foo.y); getfoo(foo); system.out.println(foo.x+", "+foo.y); } static void getfoo(foo f){ f.x=2; f=new foo(); f.x=10; } } output:
5, 10 2, 10 why happend?
x should 10 modified value f.x=10
is correct f=new foo() create new object in heap , not point prevoise reference?
in method getfoo, variable f local variable.
when call getfoo(foo) main, variable indeed refers foo.
but once set f = new foo(), refers different object.
therefore, @ point, changing f.x not affect foo.x.