java参数传递赋值

java参数传递赋值


2024年1月9日发(作者:)

java参数传递赋值

在Java中,参数传递可以分为值传递和引用传递。

- 值传递:当将基本数据类型作为参数传递给方法时,实际上是传递了该基本数据类型的值的副本,而不是原始值本身。在方法内部对该参数的修改不会影响到原始值。

- 引用传递:当将对象作为参数传递给方法时,实际上是传递了该对象的引用,也就是内存中对象的地址。在方法内部对该参数的修改会反映到原始对象上。

需要注意的是,当引用传递的对象是可变的(例如数组或集合),并在方法内部进行修改时,原始对象也会受到影响。但是,如果在方法内部对参数进行重新赋值,将不会影响原始对象。

以下是一些示例代码来说明这两种传递方式:

```java

public class Main {

public static void main(String[] args) {

// 值传递示例

int num = 10;

n("Before method call: " + num);

valuePassingExample(num);

n("After method call: " + num);

n("----------------------------------");

// 引用传递示例

int[] array = {1, 2, 3};

n("Before method call: " +

ng(array));

referencePassingExample(array);

n("After method call: " +

ng(array));

}

public static void valuePassingExample(int num) {

num = num + 5;

n("Inside method: " + num);

}

public static void referencePassingExample(int[] array) {

array[0] = 100;

n("Inside method: " + ng(array));

array = new int[]{4, 5, 6}; // 对参数进行重新赋值,不会影响原始数组

n("Inside method (after reassignment): " +

ng(array));

}

}

```

运行结果为:

```

Before method call: 10

Inside method: 15

After method call: 10

----------------------------------

Before method call: [1, 2, 3]

Inside method: [100, 2, 3]

Inside method (after reassignment): [4, 5, 6]

After method call: [100, 2, 3]

```

可以看到,在值传递的示例中,方法内部对参数进行了修改,但对原始值没有影响。而在引用传递的示例中,方法内部对参数进行修改后,原始数组也发生了变化。但是当对参数进行重新赋值时,不会影响原始数组。


发布者:admin,转转请注明出处:http://www.yc00.com/web/1704749374a1369238.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信