Why is this Java application printed "true"?

This is my first Hello.java class.

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 "I". I think, I understand, because of the "transfer link".

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? Does this “link passing” no longer exist? I'm confused.

+3
source share
9 answers

As you probably know, Java is the default. Wenn you pass the link, this link is copied. Of course: the link itself is copied, not the link target.

: build() h. h ( build()) - build(), h. h.name h.

2 : h . h build(). , h h build() ! h build() Hello, build().

+7

Java . , , . . .

+3

h. main. build.

build x, , h main .

Edit:

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 x){
        x = new Hello();
    }
}

, x null. x . x . h , x.

+1

h.name = "me" , h. , . h = new Hello() h () . h - , .

0

Test1.java, Hello object h to build(), main().h build().h .

. main().h = build().h => pointing same object

Test2.java, , main().h to build(), , , build().h . main().h

. main().h != build().h// .

main().h null, true.

0

.

( ) , , , . .

    public static void main(String[] args){
           String str = null;
           System.out.println(getString(str)== null);
   }

    public static String getString(String s){
            s = new String();
            return s;
    }

false

0

:

1) "h" null

2) "void build (Hello h)", ( "h" ), ( , , COPIED).

3) When you do "h = new Hello ()", you then change the new variable "h" in the method, pointing to a new instance of Hello (new Hello ()).

The original variable called "h" does not change.

Just like a pie.

0
source

Since h is zero.

-1
source

Source: https://habr.com/ru/post/1745096/


All Articles