Java函数传参方式及示例
发布时间:2023-10-11 02:36:59
在Java中,函数传参方式有三种:传值调用、传址调用和传引用调用。
1. 传值调用(Call by Value):
传值调用是指将参数值复制一份传递给函数,在函数内部对参数的修改不会影响到原始的参数。这种传参方式适用于基本数据类型。
示例:
public class Main {
public static void main(String[] args) {
int a = 10;
System.out.println("Before modifyValue: " + a);
modifyValue(a);
System.out.println("After modifyValue: " + a);
}
public static void modifyValue(int value) {
value = 20;
System.out.println("Inside modifyValue: " + value);
}
}
输出结果:
Before modifyValue: 10 Inside modifyValue: 20 After modifyValue: 10
可以看到,虽然在函数内部将value修改为20,但是对原始的参数a没有任何影响。
2. 传址调用(Call by Address):
传址调用是指将参数的地址(指针)传递给函数,在函数内部可以通过地址修改参数的值。这种传参方式适用于数组类型。
示例:
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.print("Before modifyArray: ");
printArray(arr);
modifyArray(arr);
System.out.print("After modifyArray: ");
printArray(arr);
}
public static void modifyArray(int[] array) {
array[0] = 10;
System.out.print("Inside modifyArray: ");
printArray(array);
}
public static void printArray(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
}
输出结果:
Before modifyArray: 1 2 3 4 5 Inside modifyArray: 10 2 3 4 5 After modifyArray: 10 2 3 4 5
可以看到,虽然在函数内部修改了数组的第一个元素为10,对原始数组产生了改变。
3. 传引用调用(Call by Reference):
传引用调用是指将参数的引用传递给函数,在函数内部对参数的修改会影响到原始的参数。这种传参方式适用于引用数据类型(例如对象)。
示例:
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 20);
System.out.println("Before modifyStudent: " + student);
modifyStudent(student);
System.out.println("After modifyStudent: " + student);
}
public static void modifyStudent(Student std) {
std.setAge(30);
System.out.println("Inside modifyStudent: " + std);
}
}
class Student {
private String name;
private int age;
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
输出结果:
Before modifyStudent: Student{name='Alice', age=20}
Inside modifyStudent: Student{name='Alice', age=30}
After modifyStudent: Student{name='Alice', age=30}
可以看到,尽管在函数内部通过setAge修改了学生对象的年龄,对原始的学生对象student产生了改变。
总结:
- 传值调用:适用于基本数据类型,函数内部对参数的修改不会影响到原始的参数。
- 传址调用:适用于数组类型,函数内部可以通过地址修改参数的值。
- 传引用调用:适用于引用数据类型,函数内部对参数的修改会影响到原始的参数。
