【常见面试题】JAVA参数传递机制(传值or传地址)
-
CSND博客: JAVA参数传递机制(传值or传地址)
-
码云源码: lishuoboy-interview
一、先上结论
-
形参是基本数据类型:
- 传递数据值(复制一份)
-
实参引用数据类型
- 传递地址值
- 注意: 特殊的类型:String、包装类等对象不可变性(final类),所以修改时会创建新对象
二、测试代码
public class PassParam {
public static void main(String[] args) {
int i = 1;
int[] arr = {1, 2, 3};
User user = new User();
Integer num = 200;
String str = "hello";
change(i, arr, user, num, str);
System.out.println("i = " + i); // 1
System.out.println("arr = " + Arrays.toString(arr)); // [2, 2, 3]
System.out.println("user.age = " + user.age); // 19
System.out.println("num = " + num); // 200
System.out.println("str = " + str); // hello
}
public static void change(int i, int[] arr, User user, Integer num, String str) {
i += 1;
arr[0] += 1;
user.age += 1;
num += 1;
str += " world";
}
}
class User {
int age = 18;
}
输出结果
i = 1 arr = [2, 2, 3] user.age = 19 num = 200 str = hello