关于java:Java中的传递是值传递

Java中的参数类型

  • 形式参数,即形参
  • 理论参数,即实参
public static void main(String[] args) {
        int i = 0;
        run(i);//变量 i 即理论参数
    }

public static void run(int a) {//变量 a 即形式参数
    System.out.println(a);
}

Java中的两种参数传递状况

  • 值传递:指在进行函数办法调用时,将理论参数复制一份到函数办法内,在函数办法内对参数进行的批改操作,将不会影响到理论参数,则称为【值传递】。
  • 援用传递:指在进行函数办法调用时,将理论参数的地址援用间接传递到函数办法内,在函数办法内对参数进行的批改,将影响到理论参数,则称为【援用传递】。

案例一:

public static void main(String[] args) {
        int i = 0;
        run(i);//变量 i 即理论参数
        System.out.println(i);//后果是:0
    }

public static void run(int a) {//变量 a 即形式参数
    a = 10;
    System.out.println(a);//后果是:10
}

变量i,初始值是:0,以理论参数传递给办法run后,在办法体内对变量进行了批改,最终再次输入变量i,仍旧是原值:0。即,合乎第一种参数传递状况:【值传递】。

案例二:

public static void main(String[] args) {
        String msg = "hello world";
        run(msg);
        System.out.println(msg);//后果是:hello world
    }

public static void run(String str){
    str = new String("haha");//成果等同于:str = "haha";
    System.out.println(str);//后果是:haha
}

变量msg,初始值是:hello world,以理论参数传递给办法run后,在办法体内对变量进行了批改,最终再次输入变量msg,仍旧是原值:hello world。即,合乎第一种参数传递状况:【值传递】。

案例三:

public static void main(String[] args) {
        Student stu = new Student("张三", 7);
        System.out.println(stu);//此案例输入后果:com.study.demo13.ArgsTest$Student@23fc625e
        run(stu);
        System.out.println(stu);//此案例输入后果:com.study.demo13.ArgsTest$Student@23fc625e
    }

public static void run(Student student) {
    student = new Student();
    student.setName("王五");
    student.setAge(12);
    System.out.println(student);//此案例输入后果:com.study.demo13.ArgsTest$Student@3f99bd52
}

static class Student {
    public String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

对象stu,以理论参数传递给办法run后,在办法体内对对象进行了批改,最终再次输入对象stu,仍旧是原对象的援用地址。即,合乎第一种参数传递状况:【值传递】。


总结:
Java中的参数传递是值传递。

判断实参内容是否发生变化,判断根据是,次要看参数传递的是什么,如果参数传递的是援用地址,则查看执行办法函数,实参前后的地址是否发生变化。

案例三中,实参对象前后的援用地址没有变动,则传递的参数是值传递。