First, there is only value passing in Java. So here’s the problem. Look at this code

class Person{
    public String name;
    public int age;
    Person(String name, int age){
        this.name = name;
        this.age = age; }}class Test{
    public static void updateName(Person person){
        person.name = "qicha";
    }
    public static void main(String[] args) {
        Person person = new Person("mogu".20);
        updateName(person);
        System.out.println(person.name);
    }
}
inputs:qicha
Copy the code

When you look at the output, you might wonder, right? Isn’t value only passable? Why did the modification succeed ?????

Java only passes values, but when you pass an object, you don’t pass the object, you pass a reference to the object. That is, the person in update and the Person in main point to the same block of memory.

So you can modify properties in an object by reference.

What if we just update this object and create a new one, which we can’t do, and create a new one is actually a new address, so we might have a new problem, because it points to the same address.

The reason is that the person in the update now points to the new address.

This is because, in the program, different variables are stored in different places, the variable name is stored in the stack, while the contents of new are stored in the heap.