[Logo]
Forums Register Login
java pass by copy, or pass by reference?
// Test1.java
import java.util.*;
public class Test1 {
public static void main(String [] a){
Test1 t=new Test1();
java.util.Date d=new java.util.Date();
t.foo(d);
System.out.println(d);
}
public void foo(java.util.Date p){
long newTime=p.getTime()+60*60*24*1000;
p.setTime(newTime);
}
}
// Test.java (RMH p453)
public class Test {
public static void main(String [] a){
Test t=new Test();
java.util.Date d=new java.util.Date();
t.foo(d);
System.out.println(d);
}
public void foo(java.util.Date p){
p=new java.util.Date(0);
}
}
The Test.java output result is the current date. It is pass-by-copy.
The Test1.java output result is the next date. It is pass-by-reference.
Why?
It is common statement that java pass primitive data by value and it pass Object data by references. More precisely it should say that java pass Object date type a copy of the reference to the object.

In Test, the foo method try to assign the passed reference to refer to new
date. That is OK inside the method. But it is a copy of orignail reference so the original reference still point to the old date it is assigned.

In the Test1, you are not try to chang the passed in reference, but you are
change the state of the object the passed in reference points to. Since both the passed in copy and oringinal reference points to the same object,
that same objects state is changed.
Java is always pass by copy. In the case of object refernces, the thing copied is the reference to the object, rather than the object itself.
Java is call by value for primitives..
and call by value-reference for Objects...

That means in case of objects the reference is passed as call by value..
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Nov 17, 2017 13:02:53.