面试题答案
一键面试值传递示例代码
public class ValueTransferExample {
public static void main(String[] args) {
int num = 10;
System.out.println("调用changeValue前 num 的值: " + num);
changeValue(num);
System.out.println("调用changeValue后 num 的值: " + num);
}
public static void changeValue(int number) {
number = 20;
}
}
值传递结果解释
在上述代码中,main
方法里定义了一个 int
类型变量 num
并赋值为 10
。然后调用 changeValue
方法并传入 num
。在 changeValue
方法中,虽然对参数 number
赋值为 20
,但这只是改变了 number
这个局部变量的值,num
本身的值并没有改变。因为 int
是基本数据类型,在方法调用时是值传递,即传递的是变量的值的副本,对副本的修改不会影响原变量。
引用传递示例代码
class Student {
String name;
public Student(String name) {
this.name = name;
}
}
public class ReferenceTransferExample {
public static void main(String[] args) {
Student student = new Student("Alice");
System.out.println("调用changeName前 student 的name: " + student.name);
changeName(student);
System.out.println("调用changeName后 student 的name: " + student.name);
}
public static void changeName(Student stu) {
stu.name = "Bob";
}
}
引用传递结果解释
在这段代码中,main
方法创建了一个 Student
对象,并将其引用赋给 student
变量。然后调用 changeName
方法并传入 student
。在 changeName
方法中,通过 stu
引用修改了对象的 name
属性。由于 Student
是引用数据类型,在方法调用时是引用传递,即传递的是对象的引用,通过这个引用可以操作同一个对象,所以原对象的 name
属性被改变了。