Pass Value---Passing basic data type parameters
Copy Code code as follows:
public class passvalue{
static void Exchange (int a, int b) {//static methods, exchanging a,b values
int temp;
temp = A;
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 passing, the main method can only invoke static methods
System.out.println ("After call:" + "i=" + i + "T" + "J =" + j);
}
}
Run Result:
Copy Code code as follows:
Before call:i = ten j = 100
After call:i = ten j = 100
Description: Invoke Exchange (I, j), the actual parameter i,j values are passed to the corresponding formal parameter a,b, and when the Method Exchange () is executed, the change of the value of the formal parameter a,b does not affect the values of the actual parameters I and J, and the values of I and J do not change before and after the call.
Reference passing---object as argument
Copy Code code as follows:
Class book{
String name;
Private Folat Price;
Book (String n, float) {//constructor method
name = N;
Price = P;
}
static void Change (book A_book, String N, float p) {//static method, object as parameter
A_book.name = n;
A_book.price = p;
}
public void output () {//instance method, output 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); Reference passing, passing the reference to object B, modifying the value of object B
System.out.print ("after Call:\t"); After the call
B.output ();
}
}
Run Result:
Copy Code code as follows:
Before Call:name:java2 price:32.5
After call:name:c++ price:45.5
Note: When calling change (b, C + +, 45.5f), object B is used as the actual parameter to pass the reference to the corresponding formal parameter a_book, and A_book also points to the same object, which has two reference names: B and A_book. When executing method change (), the A_book action on the formal parameter is the operation of the actual parameter B.