• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java pass by copy, or pass by reference?

 
bird cao
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
// 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?
 
Jack Zhou
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Richard Monson-Haefel
author
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Andy Smith
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic