请问下面两端代码public class TestValue {
public static void main(String[] args) {
int a=10;
test(a);
System.out.println("The argument a is "+a);
}
public static void test(int a){
a =1;
System.out.println("The parameter is: "+a);
}
}
得到结果:
The parameter is: 1
The argument a is 10
我可以理解形参值的改变未能影响到实参,所以形参值在test方法中被重新定义了,而实参值仍保留10.public class TestValue {
public static void main(String[] args) {
int []a = {1,2,3};
test (a);
System.out.println("The argument a[0] is "+a[0]);
}
public static void test(int[] a){
System.out.println("The original parameter is: "+a[0]);
a[0] =10;
System.out.println("The parameter is: "+a[0]);
}
}
得到的结果:
The original parameter is: 1
The parameter is: 10
The argument a[0] is 10
为何第二段代码的实参值会变化?而不是保留初始的值1?
public static void main(String[] args) {
int a=10;
test(a);
System.out.println("The argument a is "+a);
}
public static void test(int a){
a =1;
System.out.println("The parameter is: "+a);
}
}
得到结果:
The parameter is: 1
The argument a is 10
我可以理解形参值的改变未能影响到实参,所以形参值在test方法中被重新定义了,而实参值仍保留10.public class TestValue {
public static void main(String[] args) {
int []a = {1,2,3};
test (a);
System.out.println("The argument a[0] is "+a[0]);
}
public static void test(int[] a){
System.out.println("The original parameter is: "+a[0]);
a[0] =10;
System.out.println("The parameter is: "+a[0]);
}
}
得到的结果:
The original parameter is: 1
The parameter is: 10
The argument a[0] is 10
为何第二段代码的实参值会变化?而不是保留初始的值1?
其实,数组是保存在 堆内存中的. 你看一下数组的 构造方式有一种就是 String[] arg = new String[]{"a","s","d"};
你说 new 出来的东西放置到哪里呢.对吧.所以 内存地址已经做了修改.这是一个引用传递,不是一个简单的值传递啊.
a=new int[3]; //在方法里重新给变量赋值。
看看结果。