Java review---value reference and reference passing

Before talking about passing by value and passing by reference, I think I should first talk about what formal parameters and actual parameters are:

  • Formal parameters: refers to the parameters that need to be passed in when a method is called, and the parameters of the method passed in.
  • Argument: Refers to the actual value passed in when a method is called.

Let me talk about the definition first:

  • Value transfer: When a method is called, the actual parameter passes a copy of its content into the method through the formal parameter.
  • Pass by reference: When a method is called, the actual parameter passes its address to the formal parameter.

Pass by value

For value passing, it is generally for the basic data types in Java. For example, I have a method that needs to pass in an int value i, and then the code inside is i=i+1, if I pass in an i again , I output this i, there is no change in the value before and after the input.

Because he just passed the value of the actual parameter i to the formal parameter i, the operations in the method are all for the formal parameter i, so for the actual parameter i, the operations in the method are completely useless for him, so the actual The value of parameter i remains unchanged.

Pass by reference

Passing by reference is different. The simplest example of passing by reference is the pointers in C and C++. For example, if I need to exchange the values ​​of two variables, I can write a swap function to pass the pointers of the two variables in.

Does Java pass by reference?

But in fact, it can be said that Java does not pass by reference. Let’s take an example. Let’s say that I have a class Person with some getset methods. Then I create a new Person object in the main method, and then call a method. The method needs to pass in the person object, and in the method This object calls the set method, and the output is indeed new data. But if I make the person object equal to the new Person construction method in the method, if it is passed by reference, he will output the data of my new Person object, but he still outputs the original data, so Java only has value passing.

public static void PersonCrossTest(Person person){
    
    
		System.out.println("传入的person的name:"+person.getName());
		person=new Person();//加多此行代码
    person.setName("我是张小龙");
    System.out.println("方法内重新赋值后的name:"+person.getName());
}

Guess you like

Origin blog.csdn.net/why1092576787/article/details/114702983