Pass value --- Pass basic data type parameters
Copy codeThe Code is as follows: public class PassValue {
Static void exchange (int a, int B) {// static method, exchanging values of a and B
Int temp;
Temp =;
A = B;
B = temp;
}
Public static void main (String [] args ){
Int I = 10;
Int j = 100;
System. out. println ("before call:" + "I =" + I + "\ t" + "j =" + j); // before calling
Exchange (I, j); // value transfer. The main method can only call static methods.
System. out. println ("after call:" + "I =" + I + "\ t" + "j =" + j); // after the call
}
}
Running result:Copy codeThe Code is as follows: before call: I = 10 j = 100.
After call: I = 10 j = 100.
Note: When you call exchange (I, j), the actual parameters I and j respectively pass the values to the corresponding form parameters a and B. When you execute the exchange () method, the changes in the values of the formal parameters a and B do not affect the actual values of the I and j parameters. The values of the I and j do not change before and after the call.
Reference transfer --- object as a parameterCopy codeThe Code is as follows: class Book {
String name;
Private folat price;
Book (String n, float) {// Constructor
Name = n;
Price = p;
}
Static void change (Book a_book, String n, float p) {// static method, with the object as the parameter
A_book.name = n;
A_book.price = p;
}
Public void output () {// instance method, which outputs Object Information
System. out. println ("name:" + name + "\ t" + "price:" + price );
}
}
Public class PassAddr {
Public static void main (String [] args ){
Book B = new Book ("java2", 32.5f );
System. out. print ("before call: \ t"); // before calling
B. output ();
B. change (B, "c ++", 45.5f); // transmits the reference of object B and modifies the value of object B.
System. out. print ("after call: \ t"); // after the call
B. output ();
}
}
Running result:Copy codeThe Code is as follows: before call: name: java2 price: 32.5
After call: name: c ++ price: 45.5
Note: When change (B, "c ++", 45.5f) is called, object B is used as the actual parameter and the reference is passed to the corresponding format parameter a_book, in fact, a_book also points to the same object, that is, this object has two reference names: B and a_book. When the method change () is executed, the_book operation of the formal parameter is the operation of the actual parameter B.