Pass-by-value, pass-by-reference in Java

There are no pointers in Java, only pass-by-value exists in Java! ! ! However, we often see that the passing of objects (arrays, classes, interfaces) seems to be a bit like passing by reference, which can change the value of a property in the object, but don't be fooled by this illusion, in fact, the value of the incoming function is an object reference The copy, that is, the address value of the reference is passed, so it is still passed by value.

class Emp {
    public int age;
}
public class Test {
    public static void change(Emp emp)
    {
        emp.age = 50;
        emp = new Emp();//再创建一个对象
        emp.age=100;
    }
    
    public static void main(String[] args) {
        Emp emp = new Emp();
        emp.age = 100;
        System.out.println(emp.age);
        change(emp);
        System.out.println(emp.age);
        System.out.println(emp.age);
    }
}

The output is: 100 50 50.

Guess you like

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