欢迎访问宙启技术站
智能推送

Java参数传递:如何在函数间传递数据?

发布时间:2023-06-04 13:47:34

在Java程序中,函数间的数据传递可以通过一些不同的方法来实现。这些方法包括传值和传引用两种方式。在这篇文章中,我们将介绍Java参数传递的两种方式及其使用。

1.传值

传值是指将原始数据的拷贝传递给函数,函数接收到的是原始数据的值而不是指针或者引用。

示例代码如下:

public class PassValue {
    public static void main(String[] args) {
        int num = 10;
        System.out.println("Before the function call, num is " + num);

        changeValue(num);

        System.out.println("After the function call, num is " + num);
    }

    public static void changeValue(int num) {
        num = 20;
        System.out.println("Inside the function, num is " + num);
    }
}

输出结果如下:

Before the function call, num is 10
Inside the function, num is 20
After the function call, num is 10

从上面的示例中可以看出,使用传值方式时,函数接收到的是原始数据的拷贝,对拷贝的修改不会影响原始数据。在这个例子中,函数changeValue修改了num的值,但是在main函数中num的值没有改变。

2.传引用

传引用是指将数据的地址或指针传递给函数,函数通过地址或指针来访问数据,对数据的修改会影响原始数据。

示例代码如下:

public class PassReference {
    public static void main(String[] args) {
        int[] arr = new int[]{10, 20, 30};
        System.out.println("Before the function call, arr[0] is " + arr[0]);

        changeReference(arr);

        System.out.println("After the function call, arr[0] is " + arr[0]);
    }

    public static void changeReference(int[] arr) {
        arr[0] = 20;
        System.out.println("Inside the function, arr[0] is " + arr[0]);
    }
}

输出结果如下:

Before the function call, arr[0] is 10
Inside the function, arr[0] is 20
After the function call, arr[0] is 20

从上面的示例中可以看出,使用传引用方式时,函数接收到的是原始数据的地址或指针,通过地址或指针访问数据时会直接操作原始数据。在这个例子中,函数changeReference修改了arr[0]的值,main函数中arr[0]的值也随之改变。

总结:

在Java程序中,参数传递有传值和传引用两种方式。当使用传值方式时,函数接收到的是原始数据的拷贝,对拷贝的修改不会影响原始数据;当使用传引用方式时,函数接收到的是原始数据的地址或指针,通过地址或指针访问数据时会直接操作原始数据。具体选择哪种方式取决于实际需求。