Java pass by reference

A first Java code, changes before and after the test is determined str0, str1, person

public class Test {
    public static void main(String[] args) {
        String str0 = "str0";
        String str1 = new String("str1");
        Person person = new Person("person");
        System.out.println("==========before===========");
        System.out.println(str0.getClass().getName() + ":" + str0);
        System.out.println(str1.getClass().getName() + ":" + str1);
        System.out.println(person.getClass().getName() + ":" + person.getName());
        func1(str0);
        func1(str1);
        func2(person);
        System.out.println("==========after===========");
        System.out.println(str0.getClass().getName() + ":" + str0);
        System.out.println(str1.getClass().getName() + ":" + str1);
        System.out.println(person.getClass().getName() + ":" + person.getName());
    }

    public static void func1(String str) {
        str = "chg_str";
    }

    public static void func2(Person person) {
        person.setName("chg_person");
    }
}

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

After the results:

you can see: no change str0, the value of str1, person's name has changed.
To analyze the following:
entering the draft before the function:
Before entering the function, refer to each object points to the location of its memory object

after entering the function scope, create a temporary copy function object. This is what we will str0, str1 point to the newly created object in memory.

After the function scope, the temporary disappearance of reference, this time represented by str0 still str0 not changed. Entire function process, we are operating on a temporary object.

Summary: Java is not so much a reference to the concept of relative references in C ++, I think the more appropriate indicator.
But Java references and pointers in C ++ have different
switched from wheels brother: "Like C # and other managed languages, cited the behavior is determined by your object is still, you can access your object is gone, when accessed immediately out. Xiang. pointer no way, he will first destroy your global state, finally ending in a strange place, but you can not see is why. this is a good place than his hands. "

Guess you like

Origin www.cnblogs.com/YuanJieHe/p/12534861.html