Why this java application print "true"?

Posted by user292084 on Stack Overflow See other posts from Stack Overflow or by user292084
Published on 2010-05-12T11:30:22Z Indexed on 2010/05/12 11:34 UTC
Read the original article Hit count: 222

Filed under:

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.

© Stack Overflow or respective owner

Related posts about java