答:值传递。
对于基础数据类型,直接将值复制传给形参。
对于引用数据类型,直接将引用的地址值复制传给形参,形参根据地址值找到相应的对象。如果直接改变形参对象的内容,相应的实参对象内容也会改变,如果形参新建对象,则形参的改变不会影响实参对象。
证明:
1、传递引用类型参数,改变实参
@ToString
@AllArgsConstructor
@Setter
static class Student{
int age;
String name;
}
public static void main(String[] args) {
Student student= new Student(15, "张三");
System.out.println(student);
System.out.println("student的地址:" + student.hashCode());
change(student);
System.out.println(student);
}
public static void change(Student student2) {
student2.setName("李四");
System.out.println("student2的地址:" + student2.hashCode());
}
logcat:
MainActivity.Student(age=15, name=张三)
student的地址:1555896325
student2的地址:1555896325
MainActivity.Student(age=15, name=李四)
从上可以知道,实参和形参指向的是相同堆内存地址,实参把自己的引用地址传递给了形参,所以形参和实参指向了相同的对象,形参的修改影响到了实参。虽然实参的内容可以被改变,但是实参的引用并未改变,所以也是值传递,这里的值是引用类型的地址值。
image.png
2、传递引用类型参数,不影响实参
static class Student{
int age;
String name;
}
public static void main(String[] args) {
Student student= new Student(35, "Java");
System.out.println(student);
System.out.println("student的地址:" + student.hashCode());
change(student);
System.out.println(student);
}
public static void change(Student student2) {
student2 = new Student(20, "C++");
System.out.println("student2的地址:" + student2.hashCode());
}
logcat:
MainActivity.Student(age=35, name=Java)
student的地址:1555896325
student2的地址:616945236
MainActivity.Student(age=35, name=Java)
以上可看出,实参传递的是地址值,形参p2在方法中指向了新地址值(地址整数表示617901222)的对象,但并未改变实参的指向(地址整数表示1554547125)。
image.png