java parameter passing problem

/*
   Parameter passing problem in method call
      1 Method parameters are primitive data types
*/
public class MethodDemo_3{
    public static void main(String[] args){
        int a = 1 ;
        int b = 2 ;
        change(a,b);
        System.out.println(a);//1
        System.out.println(b);//2
        /*See the memory map for details. After the change runs in the method stack, no return value is given.
        That is to say, it goes out of the stack after running, and has nothing to do with a and b in main*/
    }
    public static void change(int a,int b){
        a = a+b;
        b = b+a;
    }
}

/*
   Parameter passing problem in method call
      2 The method parameter is a reference type
        The memory address is passed
*/
public class MethodDemo_4{
    public static void main(String[] args){
        int [] arr = {1,2,3,4};
        System.out.println(arr[2]);//3
        change(arr);
        System.out.println(arr[2]);//100, see the memory map for the reason
        // arr in main and arr in change point to the same memory address, and both are changed
    }
    public static void change(int[] arr){
        arr[2] = 100;
    }
    public static void change(int a,int b){
        //overload the above composition method
        a = a+b;
        b = b+a;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324764160&siteId=291194637