called by value (calls by value): Indicates that the method received the value supplied by the caller
Invoke by reference (call by reference): Indicates that the method received the address provided by the caller
A method can modify the value of the variable that corresponds to the passed reference , and cannot modify the value of the variable to which the transfer value is called
Understand:
For Java, there is no reference call, it is always called by value
How to understand the Scarlet Letter? method is to get a copy of all parameter values, and the method cannot modify the contents of any variable values passed to it
Example 1:
Public Static voidMain (string[] args) {inttemp =0; intx =Ten; inty = One; System. out. println ("Before:"+ x +" "+y); //x = ten, y = One Temp = y; y = x; x = temp; System. out. println ("After :"+ x +" "+y); //x = one, y = ten }
Example 2:
Public Static voidMain (string[] args) {inttemp =0; intx =Ten; inty = One; System. out. println ("Before:"+ x +" "+y); //x = ten, y = One Change (x, y); System. out. println ("After :"+ x +" "+y); //x = ten, y = One} Public Static voidChangeintXinty) {inttemp =0; Temp=y; Y=x; X=temp; }
As we can see, a method can not change the basic data type parameter but can change the parameter by reference type :
Example:
Public Static voidMain (string[] args) {Test T1=NewTest ("James", the);Plus (t1); System. out. println (T1.age); //Output Public Static voidPlus (Test t) {t.age+=Ten; }}classTest {String name; intAge ; PublicTest (String name,intAge ) {super (); This. Name =name; This. Age =Age ; }
Finally, let's try to test whether the reference type can be exchanged for objects:
Example:
Public Static voidMain (string[] args) {Test T1=NewTest ("James", the); Test T2=NewTest ("Alice", -); System. out. println (T1 +" "+T2); //t1 = [email protected], t2 = [email protected] swap (t1, T2); System. out. println (T1 +" "+T2); //t1 = [email protected], t2 = [email protected] } Public Static voidSwap (test T1, test T2) {Test temp=T1; T2=T1; T1=temp; }}classTest {String name; intAge ; PublicTest (String name,intAge ) {super (); This. Name =name; This. Age =Age ; } Publicinteger Plus (integer age) { age+=Ten; returnAge ; }
is still impossible to achieve
Summarize:
- A method cannot modify the parameters of a base data type
- A method cannot modify the state of an object parameter
- Object parameters can be changed by object reference
Understanding of reference passing and value passing in Java