_ The value of a parameter transfer method transfer 11

Method of transmission parameters - the value transfer

Java variables, when the shape is passed to the process parameters for actually transmitting a copy of the value of the variable, not the variable itself

This Java parameter passing mechanism we call for: value passed (just transfer value)

public class MethodParamDemo01 {
    public static void main(String[] args) {
        int number = 100 ; // 实参!
        System.out.println("调用方法前输出number:"+number); // 1 100
        change(number); // == change(100)
        System.out.println("调用方法后输出number:"+number); // 4 100
    }

    public static void change(int number){ // 形参
        System.out.println("方法中修改前输出number:"+number); // 2 100
        number = 200 ;
        System.out.println("方法中修改后输出number:"+number); // 3 200
    }
}

pay attention

Reference data type of the variable passed is a copy address

Reference data type of a variable as a parameter passed to the method parameter, in fact, a copy of the reference value is the address of the transmission data type of a variable, the value still meet delivery!

Since multiple addresses are pointing to the same object, so the party changed, see the other side of the data is also changed!

public class MethodParamDemo02 {
    public static void main(String[] args) {
        // 1.定义一个数组
        int[] arrs = new int[]{10 , 20 , 30 };
        System.out.println(arrs);    // 输出数组地址 [I@4dd8dc3
        System.out.println(arrs[0]); // 10
        System.out.println(arrs[1]); // 20
        System.out.println(arrs[2]); // 30
        System.out.println("调用方法前以上输出内容-----------");

        // 2.调用一个方法:传入数组给它,其实传输的是数组变量存储的地址副本
        changeArray(arrs); // ==  changeArray([I@4dd8dc3)

        System.out.println(arrs[0]); // 10
        System.out.println(arrs[1]); // 2000  注意:这里已经变化了!
        System.out.println(arrs[2]); // 30
        System.out.println("调用方法后以上输出内容-----------");
    }

    public static void changeArray(int[] arrs){
        System.out.println(arrs);  // 输出数组地址 [I@4dd8dc3
        System.out.println(arrs[0]); // 10
        System.out.println(arrs[1]); // 20
        System.out.println(arrs[2]); // 30
        System.out.println("在方法中修改数组前以上输出内容-----------");
        arrs[1] = 2000;
        System.out.println(arrs[0]);  // 10
        System.out.println(arrs[1]);  // 2000
        System.out.println(arrs[2]);  // 30
        System.out.println("在方法中修改数组后以上输出内容-----------");
    }
}

Published 34 original articles · won praise 16 · views 294

Guess you like

Origin blog.csdn.net/qq_41005604/article/details/105165563