java-error-prone

Parameter passing

When passing basic data types:

public class ArgumentsDemo01 {
    
    
	public static void main(String[] args) {
    
    
		int a=5;
		int b=10;
		change(a, b);//调用方法时,传入的数值称为实际参数
		System.out.println("a=" + a);
		System.out.println("b=" + b);
	}

	public static void change(int a, int b){
    
    //方法中指定的多个参数称为形式参数
		a=200;
		b=500;
	}
}

Output:
a=5
b=10

The space is cleared after the method change runs, and it does not affect a, b in the main method

When passing reference data types:

public class ArgumentsDemo02 {
    
    
	public static void main(String[] args) {
    
    
		int[] arr = {
    
     1, 2, 3 };
		change(arr);// 调用方法时,传入的数值称为实际参数
		
		for (int i = 0; i < arr.length; i++) {
    
    
			System.out.println(arr[i]);
		}
	}

	public static void change(int[] arr) {
    
    // 方法中指定的多个参数称为形式参数
		for (int i = 0; i < arr.length; i++) {
    
    
			arr[i] *= 2;
		}
	}
}

Output:
2
4
6

Reason: The memory address is passed when passing parameters

Guess you like

Origin blog.csdn.net/xiaonuanhu/article/details/107716923