This is my first Class Hello.java
public class Hello {
String name = "";
}
This is my second Class Test1.java
public class Test1 {
public static void main(String[] args) {
Hello h = new Hello();
Test1 t = new Test1();
t.build(h);
System.out.println(h.name);
}
void build(Hello h){
h.name = "me";
}
}
When I run Test1.java, it prints “me”. I think I understand, because of “reference transfer”.
This is my third Class Test2.java
public class Test2 {
public static void main(String[] args) {
Hello h = null;
Test2 t = new Test2();
t.build(h);
System.out.println(h == null);
}
void build(Hello h){
h = new Hello();
}
}
When I run Test2.java, it prints “true”, why ? Is it “reference transfer” no longer? I am confused.
As you probably know, Java is call-by-value. Wenn you pass a reference, that reference gets copied. To be sure: The reference itself and not the reference’s target gets copied.
Let’s have a look at your first sample: When calling
build(), the referencehwill be copied. Becauseh(the copy inbuild()) does not get overwritten somewhere inbuild(), it always points to the memory location of the originalh. So changingh.nameaffects the originalh.Sample 2 is different: reference
hgets copied, too. Buthgets overwritten inbuild(). The effect is that the originalhand thehinbuild()point to different memory locations! Thehinbuild()points to the newly generatedHelloobject, which will be garbage collected somewhen after the return of methodbuild().