当前位置:网站首页>Parameter passing mechanism of member methods

Parameter passing mechanism of member methods

2022-07-05 00:26:00 The learning path of Java Rookies

Parameter transfer mechanism of basic data type

The basic data type passes a value , The change of formal parameter value will not lead to the change of actual parameter value

public class MethodParameter01 {
    

// Write a  main  Method 
public static void main(String[] args) {
    

int a = 10;
int b = 20;
// establish  AA  object   name  obj
AA obj = new AA();
obj.swap(a, b); // call  swap

System.out.println("main  Method  a=" + a + " b=" + b);//a=10 b=20
}
}
class AA {
    
public void swap(int a,int b){
    
System.out.println("\na  and  b  Value before exchange \na=" + a + "\tb=" + b);//a=10 b=20
// It's done  a  and  b  In exchange for 
int tmp = a;
a = b;
b = tmp;
System.out.println("\na  and  b  Value after exchange \na=" + a + "\tb=" + b);//a=20 b=10
}
}

Here is my memory analysis of the above code
 Insert picture description here
When swap After method execution , It's out of the stack , Memory free , And then go ahead and do it main Method ,swap Formal parameters in method a,b Changes that occur do not affect changes in arguments

The parameter passing mechanism of reference data type

 Insert picture description here

Memory resolution
 Insert picture description here

summary

When parameters are passed , The basic data type is a value , Parameter changes do not affect argument changes
The reference data type passes the memory address , The change of formal parameters will affect the change of arguments

原网站

版权声明
本文为[The learning path of Java Rookies]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141125149383.html