Java方法调用中对形参的更改是否影响实参?涉及到Java的方法调用的传参机制,本文结论是Java使用值传递,案例分析如下文
值传递和引用传递
值传递是指形参拷贝一份实参的数值
引用传递是指形参就是实参对象本身
形参是独立的拷贝
无论传递的是基本类型还是引用类型,形参是对实参值独立的一份拷贝,意味着形参与实参属于不同的内存空间,修改形参不影响实参
public class Reference { private String string; public Reference(String string) { this.string = string; } // getter and setter public static void main(String[] args) { test0(); test1(); test2(); } }
- 传递基本类型参数
尽管方法调用中修改了形参为1,但调用后返回原实参,实参未经修改
public static void test0() {
int num = 0;
invoke0(num);
System.out.println(num);
}
public static void invoke0(int basic) {
System.out.println(basic);
basic = 1;
System.out.println(basic);
}
0
1
0
- 传递引用类型参数
形参指向新引用,但实参未经更改,说明形参和实参是两个不同的内存地址空间,修改各自的内存不影响对方的内存
public static void test1() {
Reference rParam = new Reference("s");
System.out.println("before invoke : " + rParam);
invoke1(rParam);
System.out.println("after invoke : " + rParam);
}
public static void invoke1(Reference fParam) {
System.out.println("before change : " + fParam);
fParam = new Reference("s");
System.out.println("after change : " + fParam);
}
before invoke : copy.Reference@1b6d3586
before change : copy.Reference@1b6d3586
after change : copy.Reference@4554617c
after invoke : copy.Reference@1b6d3586
修改引用内存会修改两参
实参和形参仅是对象地址的引用,当修改引用地址的内存空间时,将实际更改堆内存中的对象
public static void test2() {
Reference rParam = new Reference("s");
System.out.println("before invoke : " + rParam + " | content : " +rParam.getString());
invoke2(rParam);
System.out.println("after invoke : " + rParam + " | content : " +rParam.getString());
}
public static void invoke2(Reference fParam) {
System.out.println("before change : " + fParam + " | content : " +fParam.getString());
fParam.setString("c");
System.out.println("after change : " + fParam + " | content : " +fParam.getString());
}
before invoke : copy.Reference@1b6d3586 | content : s
before change : copy.Reference@1b6d3586 | content : s
after change : copy.Reference@1b6d3586 | content : c
after invoke : copy.Reference@1b6d3586 | content : c