值传递、引用传递、数组传递的区别

来源:互联网 发布:雅思精听软件 编辑:程序博客网 时间:2024/06/06 16:46

先不说,上个小程序:

import java.util.Arrays;public class 值_引用_数组不同的传递 {public static void change(int a,String str ,int[] arr){a++;str = "hello world";arr[0] = 9;}public static void main(String[] args) {int a = 1;int[] arr = {1,3,5,3,2};String str = "hello";change(a,str,arr);System.out.println("a: "+a);System.out.println("str: "+str);System.out.println("arr: "+Arrays.toString(arr));}}
结果:

a: 1
str: hello
arr: [9, 3, 5, 3, 2]


从上面小程序可知:

str是String类型的引用,a是基本类型变量,arr是数组名,也是数组对象的引用

i是整型值,只是把值copy了一份给change()方法,在方法的变化是不改变的源i的。

在change()方法里,str="hello world",是一个新的对象把首地址放在引用变量str上;

而arr[0]=9;因为传的是数组的引用,而此时arr[0]=9;是对数组元素的操作,能修改源数组的内容;



0 0