java parameter passing problem

Problem description: When passing java parameters, if the parameter is a basic data type or a reference data type, will the value of the parameter itself change after the transfer is completed?

Code Quiz:
1: Pass Basic Data Types

package com.test.other;

public class ParamTransfer {

    private int money;

    public static void main(String[] args){
        ParamTransfer pt=new ParamTransfer();
        pt.money=10;
        pt.method(pt.money);

        System.gc();

    }

    public void method(int i) {  //此处为传数值,只是把money的值拷贝给了i
        // TODO Auto-generated method stub
        System.out.println("传入的值:"+i);
        i=i*5;
        System.out.println("改变后的i值:"+i);

        System.out.println("money的值:"+this.money);
    }


}

Output after run:
Value passed in: 10 Value
of i changed: 50
Value of money: 10

2: Pass by reference data type

package com.test.other;


 class Time{

     int h;

     int f;

     int s;

     Time(int h, int f, int s){
         this.h=h;
         this.f=f;
         this.s=s;
     }
 }

public class ObjectParamTransfer {

    private Time t;

    public static void main(String[] args){
        ObjectParamTransfer opt=new ObjectParamTransfer();
        opt.t=new Time(11,12,13);

        opt.method(opt.t);

        System.out.println("改变后t的值(方法外): h="+opt.t.h+" f="+opt.t.f+" s="+opt.t.s);

    }

    private void method(Time tt) {  //此处为内存地址传递
        // TODO Auto-generated method stub

        System.out.println("传入后tt值:h="+tt.h+" f="+tt.f+" s="+tt.s);

        tt.h=1;
        tt.f=2;
        tt.s=3;

        System.out.println("改变后tt值:h="+tt.h+" f="+tt.f+" s="+tt.s);

        System.out.println("改变后t的值(方法内): h="+this.t.h+" f="+this.t.f+" s="+this.t.s);
    }

}

Output
after running: tt value after passing in: h=11 f=12 s=13
tt value after changing: h=1 f=2 s=3
Value of t after changing (in the method): h=1 f=2 s =3
value of t after change (outside the method): h=1 f=2 s=3

Conclusion:
Java always performs value-by-value calls when passing parameters (in the runtime stack, the processing of basic types and references is the same, both are value-by-value, so if it is a method call by reference, it can also be understood as The "pass by reference value" call by value, that is, the reference is handled exactly the same as the basic type. But when entering the called method, the value of the passed reference is interpreted (or searched) by the program to the object in the heap ,
only corresponds to the real object at this time. If the modification is made at this time, the modification is to refer to the corresponding object, not the reference itself, that is, the data in the heap is modified. So this modification can be maintained). Primitive data types are passed by copy value.

Guess you like

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