[Java] Understanding java parameter passing always adopts value passing/calling by value

Refer to "Java Core Technology Volume I"

call by value

All Java method parameters are called by value , and the method gets a copy of all parameter values .

the type of the method parameter

There are two types of method parameters

  • Primitive Data Types (Number, Boolean)
  • object reference

An internal method cannot be of a basic data type, but can modify the content of an object through an object reference .
As shown in the following code

  public static void main(String[] args) {
    
    
      Employee employee = new Employee(100);
      System.out.println(employee.getSalary());
      addSalary(employee);
      System.out.println(employee.getSalary());
  }

  public static void addSalary(Employee x){
    
    
      x.raiseSalary(200);
  }

output result

insert image description here
Explanation: What the method gets is a copy of the object reference (which can be understood as a pointer from a certain point of view, but strictly speaking, it is not a pointer),Object references and other copies refer to the same object at the same time.

The object is not called by reference! ! ! !

  • Many people think that Java uses reference calls when passing objects, which is actually not true.
  • The object is also called by value, but what is passed is a copy of the reference value, so it is still called by value
  • For a better understanding, here is a counter-example

Wrote a method that swaps two employee objects

   public static void swap(Employee x,Employee y){
    
    
       Employee temp = x;
       x = y;
       y= temp;
   }

If Java uses reference calls, then this method can interact with data effects

  Employee a = new Employee("aaaa");
  Employee b = new Employee("bbbb");
  swap(a,b);

But the method does not change the object references in the variables a and b , x and y in swap are initialized as copies of the two object references, and the swap method exchanges the references stored in the x and y variables (which can also be understood as pointing to object). x and y are discarded at the end of the final method, wasting effort.
In fact,object referenceis passed by value.

For a better understanding, use diagrams to illustrate the process of calling the above method and exchanging object references

  • before calling the method
    insert image description here
  • Initialize the swap method (just entered the swap method)
    insert image description here
  • After the method is executed, before the method is destroyed. Note the change of the x and y object references
    insert image description here
  • After the method is executed, the method is destroyed. As in the beginning, it was a waste of effort.
    insert image description here

Summarize

insert image description here

Guess you like

Origin blog.csdn.net/hhb442/article/details/131754226