一、实参和形参
实参:就是方法调用的参数。
形参:方法中定义的参数
public class Test1 {
public static void main(String[] args) {
int a=4,b=5;
//实际参数——实参a b
int Max= max(a,b);
}
//形式参数 ——形参 i j
private static int max(int i, int j) {
return i>j ? i : j;
}
}
二、值传递和引用传递
值传递:
public class Test1 {
public static void main(String[] args) {
int a = 10;
AA(a);
System.out.println("main中值为:"+a);
}
public static void AA(int a){
a = 20;
System.out.println("方法AA中值为:"+a);
}
}
方法AA中值为:20
main中值为:10
引用传递:
public class Test1 {
public static void main(String[] args) {
int [] arr = {1,2,3};
System.out.println("引用传递前:"+Arrays.toString(arr));
BB(arr);
System.out.println("引用传递后:"+Arrays.toString(arr));
}
public static void BB(int[] arr){
arr[0] = 66;
}
}
引用传递前:[1, 2, 3]
引用传递后:[66, 2, 3]
对比
值传递:实际上就是把值复制一份到方法中,方法中值改变不影响,main中的值。
引用传递:引用传递是传递对象的地址,在方法中改变值其实就是改变源对象的值。