- 值传递
方法在调用的时候,实际参数把它的值赋予给形式参数,但是形式参数的数据类型只能是基本数据类型和String。形式参数和实际参数在内存上是两个独立的变量,对形式参数的修改并不会影响实际参数的值。
public class ValuePassing {
public static void main(String[] args) {
int b = 10;
testFunction(b); // 实际参数 传入参数不会改变参数本身的值
System.out.println(b);
}
public static void testFunction(int a){ //形式参数
a=100;
}
}
- 引用传递
在方法调用时,传递的实际参数是java对象,也就是对象的内存空间的地址。而形式参数也会指向这一内存地址。注意被传递的形式参数的数据类型必须是引用数据类型
public class Student {
int age;
}
public class ReferencePassing {
public static void main(String[] args) {
Student student = new Student();
student.age = 28;
testFunction(student);
System.out.println(student.age);
}
public static void testFunction(Student student){
student.age = 18;
}
}
具体描述如下: