Java中的参数类型
1 2 3 4 5 6 7 8
| public static void main(String[] args) { int i = 0; run(i);//变量 i 即实际参数 }
public static void run(int a) {//变量 a 即形式参数 System.out.println(a); }
|
Java中的两种参数传递情况
- 值传递:指在进行函数方法调用时,将实际参数复制一份到函数方法内,在函数方法内对参数进行的修改操作,将不会影响到实际参数,则称为【值传递】。
- 引用传递:指在进行函数方法调用时,将实际参数的地址引用直接传递到函数方法内,在函数方法内对参数进行的修改,将影响到实际参数,则称为【引用传递】。
案例一:
1 2 3 4 5 6 7 8 9 10
| 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。即,符合第一种参数传递情况:【值传递】。
案例二:
1 2 3 4 5 6 7 8 9 10
| 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。即,符合第一种参数传递情况:【值传递】。
案例三:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| 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中的参数传递是值传递。
判断实参内容是否发生变化,判断依据是,主要看参数传递的是什么,如果参数传递的是引用地址,则查看执行方法函数,实参前后的地址是否发生变化。
案例三中,实参对象前后的引用地址没有变化,则传递的参数是值传递。