Java方法的参数传递机制
java中方法的参数传递方式只有一种:值传递。就是将实际参数的副本(复制品)传入方法中,其本身不会受到影响。
1、普通变量的传递
public class t {
public static void swap(int a,int b) {
int temp=a;
a=b;
b=temp;
System.out.println("swap()方法中a的值为:"+a+",b值为:"+b);
}
public static void main(String[] args) {
int a=1;
int b=2;
swap(a,b); //传入的是值,即1,2,而不a,b本身
System.out.println("交换后的a值为:"+a+",b值为:"+b);
}
}
输出结果:swap()方法中a的值为:2,b值为:1
交换后的a值为:1,b值为:2
只是将a,b的副本传入swap方法中,而main方法中的a,b本身并不改变。
2、引用类型的参数传递
class Date{
int a;
int b;
}
public class t {
public static void swap(Date dt) {
int temp=dt.a;
dt.a=dt.b;
dt.b=temp;
System.out.println("swap()方法中,a成员变量的值为:"+dt.a+",b成员变量的值为:"+dt.b);
}
public static void main(String[] args) {
Date dt=new Date();
dt.a=1;
dt.b=2;
swap(dt);
System.out.println("交换后,a成员变量的值为:"+dt.a+",b成员变量的值为:"+dt.b);
}
}
输出结果:swap()方法中,a成员变量的值为:2,b成员变量的值为:1
交换后,a成员变量的值为:2,b成员变量的值为:1
此时发现,swap方法和main方法中的输出结果一样,但是这并不是因为swap中操作的是对象本身,而是因为实例dt是一个引用(想当于c中的指针),其存放的数据是一个地址值,指向堆内存中Date对象。
main方法将dt的地址值传递给了swap方法,因此swap方法中的dt也指向了堆内存中的Date对象,因此此时无论是更改main方法还是swap方法,均会造成影响。