The JUC Series of Java Interviews: Value Passing and Reference Passing

Pass by value and pass by reference

For example

/**
 * 值传递和引用传递
 */
class Person {
    
    
    private Integer id;
    private String personName;

    public Person(String personName) {
    
    
        this.personName = personName;
    }
}
public class TransferValueDemo {
    
    

    public void changeValue1(int age) {
    
    
        age = 30;
    }

    public void changeValue2(Person person) {
    
    
        person.setPersonName("XXXX");
    }
    public void changeValue3(String str) {
    
    
        str = "XXX";
    }

    public static void main(String[] args) {
    
    
        TransferValueDemo test = new TransferValueDemo();

        // 定义基本数据类型
        int age = 20;
        test.changeValue1(age);
        System.out.println("age ----" + age);

        // 实例化person类
        Person person = new Person("abc");
        test.changeValue2(person);
        System.out.println("personName-----" + person.getPersonName());

        // String
        String str = "abc";
        test.changeValue3(str);
        System.out.println("string-----" + str);

    }
}

The final output

age ----20
personName-----XXXX
string-----abc

The execution process of changeValue1

Eight basic data types, which allocate memory in the stack, belong to value transfer

栈管运行,堆管存储

When we execute changeValue1, because int is a basic data type, the value of int = 20 is passed, which is equivalent to a copy. The age in the main method has not changed, so the output result age is still 20, which belongs to Pass by value

image-20200314185317851

The execution process of changeValue2

Because Person belongs to an object, and the memory address is passed. When changeValue2 is executed, the value of Person in the memory will be changed. This is a reference pass. Both pointers point to the same address.

image-20200314185528034

The execution process of changeValue3

String is not a basic data type, but why is it still abc after the execution is complete?

This is because of the special nature of String, when we execute String str = "abc", which will abcput constant pool

image-20200314190021466

When we execute changeValue3, we will create a new xxx without destroying abc, and then point to xxx, and then finally we output the reference in main or the abc pointed to, so the final output result is still abc

Guess you like

Origin blog.csdn.net/weixin_43314519/article/details/110195744