Java's parameter passing is quite tricky - When an object is passed to a function, you can manipulate the object's fields but you cannot manipulate object itself. The object reference is passed by value. So, you can say:
class someClass{
int i = 5;
}
class Foo
{
static void func(someClass c)
{
c.i = 3;
}
}
class MainClass{
public static void main(){
someClass c = new someClass();
System.out.println(c.i);
Foo.func(c);
System.out.println(c.i);
}
}
Expect your output to be:
5
3
Changes to the fields of c persist.
but if manipulate the object itself, this manipulation will only persist in Foo.func()
and not outside that function:
class someClass{
int i = 5;
}
class Foo
{
static void func(someClass c)
{
c.i = new someClass();
c.i = 3;
System.out.println(c.i);
}
}
class MainClass{
public static void main(){
someClass c = new someClass();
System.out.println(c.i);
Foo.func(c);
System.out.println(c.i);
}
}
Expect your output to be:
5
3
5
What has happened? c.i has the value 5 in MainClass.main()
in Foo.func()
, c itself is modified to point to another instance of someClass
, containing the value 3. However, this change is not reflected to the actual object that has been passed. The c
in Foo.func()
and MainClass.main()
are different objects now. That's why changes to the c
of Foo.func()
do not affect the c
in MainClass.main()
.