Java值传递

  • Java中只有值传递没有引用传递

1. 形参&实参

  • 形参:方法定义时的参数,形式参数
  • 实参:方法调用时的参数,实际参数
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public class ValuePassingExample {
    public static void main(String[] args) {
    int a = 5; // 实参
    modifyValue(a); // 传递实参
    System.out.println("a的值: " + a); // 输出: a的值: 5
    }

    public static void modifyValue(int value) { // 形参
    value = 10; // 修改形参的值
    }
    }

2. 值传递&引用传递

  • 值传递:方法调用时传递进去的是实参的值,方法接受的是实参值的拷贝,而不是实参本身
  • 引用传递:方法调用时传递进去的是实参的地址,此时形参就是实参,对形参的修改都会同步到实参上

3. Java中只有值传递

  • 3个案例说明Java中的值传递

案例1:基本数据类型的值传递

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
swap(num1, num2);
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}

public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("a = " + a);
System.out.println("b = " + b);
}
  • 输出结果:
1
2
3
4
a = 20
b = 10
num1 = 10
num2 = 20

案例2:引用数据类型的值传递1

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
System.out.println(arr[0]);
change(arr);
System.out.println(arr[0]);
}

public static void change(int[] array) {
// 将数组的第一个元素变为0
array[0] = 0;
}
  • 输出结果:
1
2
1
0
  • 这里传递的还是值,不过,这个值是实参的地址。也就是说change方法的参数拷贝的是arr(实参)的地址,因此,它和arr指向的是同一个数组对象。这也就说明了为什么方法内部对形参的修改会影响到实参。

案例3:引用数据类型的值传递2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Person {
private String name;
// 省略构造函数、Getter&Setter方法
}

public static void main(String[] args) {
Person xiaoZhang = new Person("小张");
Person xiaoLi = new Person("小李");
swap(xiaoZhang, xiaoLi);
System.out.println("xiaoZhang:" + xiaoZhang.getName());
System.out.println("xiaoLi:" + xiaoLi.getName());
}

public static void swap(Person person1, Person person2) {
Person temp = person1;
person1 = person2;
person2 = temp;
System.out.println("person1:" + person1.getName());
System.out.println("person2:" + person2.getName());
}
  • 输出结果:
1
2
3
4
person1:小李
person2:小张
xiaoZhang:小张
xiaoLi:小李
  • swap方法的参数person1person2只是拷贝的实参xiaoZhangxiaoLi的地址。因此,person1person2的互换只是拷贝的两个地址的互换罢了,并不会影响到实参xiaoZhangxiaoLi