Java中值传递与地址(引用)传递

值传递

值传递:方法调用时,实际参数把它的值传递给对应的形式参数,方法执行中形式参数值的改变不影响实际参数的值。

public class Explore {
	public static void main(String[] args) {
	    int  scores = 100;
	    System.out.println(scores);//100
	    test(scores);//调用函数
	    System.out.println(scores);//100
	  }
	  
	  public static void test(int a) {
	    System.out.println("***"+a);//***100
	    a = 0;
	    System.out.println(a);//0
	  }
}
输出结果
100
***100
0
100

上述代码中scores被赋值100,经过test方法将100这个值传递给了a,易知a是新定义的一个变量,即形参,当a改变时,scores(实参)不会改变,输出结果仍为100。

地址(引用)传递

引用传递:是指在调用函数时将实际参数的地址直接传递到函数中,那么在函数中对参数所进行的修改,将影响到实际参数。

public static void main(String[] args) {
    int [] scores = {100,200};
    System.out.println(scores);//[I@52e922
    System.out.println(scores[0]);//100
    test(scores);//调用函数
    System.out.println(scores[0]);//0
  }
  public static void test(int [] array) {
    System.out.println(array);//[I@52e922
    array[0] = 0;
    
  }
}
输出结果
[I@52e922
100
[I@52e922
0

这次代码中定义scores为一个int类型的一维数组;输出scores的结果为数组在栈内存中存储的地址;输出scores[0]的结果为数组在堆内存中存储的100;调用函数,由结果可知函数将存储scores数组的地址传递给了array,此时scores与array均指向栈内存中的数组存储的地址,可知array[0]=scores[0],array[1]=scores[1]。
如果对array[0]进行修改,则scores[0]也会随之而变。
与值传递相比,地址传递中函数直接对实参进行修改,没有形参。

就好比一个盒子里放了一个魔方,起初只有A知道盒子在哪,但A告诉了B; A去玩魔方,玩完将魔方放回盒子里;这时B再去玩,就是玩A剩下的;B玩完之后A再去,就是A玩B剩下的;这样AB都可以对魔方进行修改,而反馈是面向AB两人的。

发布了8 篇原创文章 · 获赞 1 · 访问量 65

猜你喜欢

转载自blog.csdn.net/weixin_46383723/article/details/104469256