Pass by value---pass basic data type parameters
Copy the code code as follows:
public class PassValue{
static void exchange(int a, int b){//Static method, exchange the values of a and b
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 call
exchange(i, j); //Value transfer, the main method can only call static methods
System.out.println("after call: " + "i=" + i + "/t" + "j = " + j);//After call
}
}
Running results:
Copy the code code as follows:
before call: i = 10 j = 100
after call: i = 10 j = 100
Note: When calling exchange(i, j), the actual parameters i and j pass their values to the corresponding formal parameters a and b respectively. When the method exchange() is executed, changes in the values of the formal parameters a and b do not affect the actual parameters. The values of i and j have not changed before and after the call.
Passing by reference --- object as parameter
Copy the code code as follows:
class Book{
String name;
private folat price;
Book(String n, float){ //Construction 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 transfer, transfer the reference of object b, modify the value of object b
System.out.print("after call:/t"); //After call
b.output();
}
}
Running results:
Copy the 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, and the reference is passed to the corresponding formal parameter a_book. In fact, a_book also points to the same object, that is, the object has two reference names: b and a_book. When executing the method change(), the operation on the formal parameter a_book is the operation on the actual parameter b.