javaSE-值传递和引用传递

1、值传递和引用传递

当参数类型是基本数据类型时,传递的是实参的值,因此无法对实参进行修改。
当参数类型是非基本数据类型时,传递的是实参内存地址的拷贝,此时形参和实参都可以对此对象的字段进行修改,但是互相无法影响对方本身。

class Person {
    String name;
    int money;
}

class Client {
    public static void main(String[] args) {
        // Create a person named Bob and he has no money.
        Person person = new Person();
        person.name = "Bob";
        person.money = 0;
        // Check the person, if he has no money, set it as null
        check(person);
        // If the person turned to null, print he has no money, otherwise print he's rich
        if (person == null) {
            System.out.println(person.name + " has no money.");
        } else {
            System.out.println(person.name + " is rich.");
        }
    }

    private static void check(Person person) {
        if (person.money <= 0) {
            person = null;
        }
    }

}

运行结果

Bob is rich //

分析:在下面代码中,传入的Person  person  是引用传递,是对原内存地址的拷贝,方法体中person=null改变的是复制地址的数据,无法对原内存地址产生影响