Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this java application print "true"?

Tags:

java

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.

like image 848
Keating Avatar asked Jul 21 '26 01:07

Keating


1 Answers

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 reference h will be copied. Because h(the copy in build()) does not get overwritten somewhere in build(), it always points to the memory location of the original h. So changing h.name affects the original h.

Sample 2 is different: reference h gets copied, too. But h gets overwritten in build(). The effect is that the original h and the h in build() point to different memory locations! The h in build() points to the newly generated Hello object, which will be garbage collected somewhen after the return of method build().

like image 65
Johannes Weiss Avatar answered Jul 22 '26 22:07

Johannes Weiss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!