五种常用的Java函数参数传递方式
发布时间:2023-11-05 07:37:38
在Java中,函数参数的传递方式有五种常用的方式。它们分别是:按值传递、按引用传递、按值-结果传递、按引用-结果传递和按传址传递。
1. 按值传递(传值调用):这是Java中最常见的参数传递方式。在按值传递中,函数的参数值被复制给函数内部的局部变量。这意味着,当函数内部修改参数的值时,外部的参数值并不会改变。
例如:
public class Main {
public static void main(String[] args) {
int x = 10;
System.out.println("Before calling the function: " + x);
changeValue(x);
System.out.println("After calling the function: " + x);
}
public static void changeValue(int value) {
value = 20;
}
}
输出结果为:
Before calling the function: 10 After calling the function: 10
2. 按引用传递(传引用调用):在按引用传递中,函数的参数值是实际对象的引用。这意味着,当函数内部修改参数的值时,外部的参数值也会改变。
例如:
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
System.out.println("Before calling the function: " + sb.toString());
changeValue(sb);
System.out.println("After calling the function: " + sb.toString());
}
public static void changeValue(StringBuilder value) {
value.append(", world!");
}
}
输出结果为:
Before calling the function: Hello After calling the function: Hello, world!
3. 按值-结果传递:在按值-结果传递中,函数的参数同时作为输入和输出。函数通过返回值将计算的结果传递给调用者。
例如:
public class Main {
public static void main(String[] args) {
int x = 10;
System.out.println("Before calling the function: " + x);
x = changeValue(x);
System.out.println("After calling the function: " + x);
}
public static int changeValue(int value) {
value = 20;
return value;
}
}
输出结果为:
Before calling the function: 10 After calling the function: 20
4. 按引用-结果传递:在按引用-结果传递中,函数的参数同时包含输入和输出。函数通过修改参数本身来传递计算结果。
例如:
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
System.out.println("Before calling the function: " + sb.toString());
changeValue(sb);
System.out.println("After calling the function: " + sb.toString());
}
public static void changeValue(StringBuilder value) {
value.append(", world!");
}
}
输出结果为:
Before calling the function: Hello After calling the function: Hello, world!
5. 按传址传递:按传址传递是指函数的参数是变量的内存地址,通过修改该内存地址所指向的值来传递参数。
在Java中,没有直接支持按传址传递的语法。但是可以通过封装对象来实现类似的效果。
例如:
public class Main {
public static void main(String[] args) {
Wrapper<Integer> value = new Wrapper<>(10);
System.out.println("Before calling the function: " + value.getValue());
changeValue(value);
System.out.println("After calling the function: " + value.getValue());
}
public static void changeValue(Wrapper<Integer> value) {
value.setValue(20);
}
}
class Wrapper<T> {
private T value;
public Wrapper(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
输出结果为:
Before calling the function: 10 After calling the function: 20
这五种常用的Java函数参数传递方式在不同的情况下有不同的应用场景。开发人员根据具体需求选择合适的传递方式,以实现预期的功能和效果。
