Java中的值传递和引用传递

233 阅读1分钟

Java中的方法的参数都是值传递,参数是基本类型,会将内存中的基本类型变量的值拷贝一份给形参;参数是引用类型,拷贝给形参的是地址值。Java中有没有引用传递?给new出来的对象.属性赋新值。 Java中的方法的参数都是值传递。
Java中有没有引用传递?

/**
 * @author admin
 * @description 值传递 & 引用传递
 */
// Application.java
public class Application {
    public static void main(String[] args) {
        Student student = new Student();

        // 值传递
        int num = 5;
        student.changeNum(num);
        System.out.println(num); // 5

        student.changeObj(student);
        System.out.println(student.name); // null

        // 引用传递
        student.changeObjSeriously(student);
        System.out.println(student.name); // 张三
    }
}
// Student.java
public class Student {
    String name;
    int age;

    public void eat () {
        System.out.println(this.name + "吃东西");
    }

    public void changeNum (int a) {
        a = 999;
    }

    public void changeObj (Student student) {
        student = new Student(); // 此处修改无效,因为是值引用,所以无法修改传进来的对象的属性
        student.name = "zs";
    }

    public void changeObjSeriously (Student student) {
        student.name = "张三"; // 引用传递
    }
}