When a variable is the most passed in method, there are two different transfer methods: value transfer and reference transfer.
Feature of value transfer: no matter whether the parameter passed in is changed in the method, the value of the variable outside the method is not affected.
Features of reference transfer: changes made to the passed parameters inside the method also affect the value of variables outside the method.
So What Are value transfer and reference transfer?
Passing of basic types (8 types) is a value transfer
All reference types (except String) are passed by reference
Strng is special. Although it is a reference type, it is a value transfer
Let's take an example to understand:
Student. java
[Java]
Package com. tianjf;
Public class Student {
Private String name;
Public Student (String name ){
Super ();
This. name = name;
}
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
@ Override
Public String toString (){
Return name;
}
}
Package com. tianjf;
Public class Student {
Private String name;
Public Student (String name ){
Super ();
This. name = name;
}
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
@ Override
Public String toString (){
Return name;
}
}
Test. java
[Java]
Package com. tianjf;
Public class Test {
Private static void changeInt (int I ){
I = 1;
}
Private static void changeStudent (Student student ){
Student. setName ("Li Si ");
}
Private static void changeString (String str ){
Str = "456 ";
}
Public static void main (String [] args ){
Int I = 0;
String str = "123 ";
Student student = new Student ("James ");
System. out. println ("Before change: \ ni:" + I + "\ n" + "student:" + student. toString () + "\ n" + "str:" + str );
ChangeInt (I );
ChangeStudent (student );
ChangeString (str );
System. out. println ("After change: \ ni:" + I + "\ n" + "student:" + student. toString () + "\ n" + "str:" + str );
}
}
Package com. tianjf;
Public class Test {
Private static void changeInt (int I ){
I = 1;
}
Private static void changeStudent (Student student ){
Student. setName ("Li Si ");
}
Private static void changeString (String str ){
Str = "456 ";
}
Public static void main (String [] args ){
Int I = 0;
String str = "123 ";
Student student = new Student ("James ");
System. out. println ("Before change: \ ni:" + I + "\ n" + "student:" + student. toString () + "\ n" + "str:" + str );
ChangeInt (I );
ChangeStudent (student );
ChangeString (str );
System. out. println ("After change: \ ni:" + I + "\ n" + "student:" + student. toString () + "\ n" + "str:" + str );
}
}
Running result: www.2cto.com
Before change:
I: 0
Student: James
Str: 123
After change:
I: 0
Student: Li Si
Str: 123
From the running results, we can see that the int and String types are not changed after the change method, but the student value has changed.
Author: tianjf0514