Analysis of the difference between value passing and reference passing in Java
- 2020-04-01 01:27:34
- OfStack
Pass value -- pass basic data type parameters
public class PassValue{
static void exchange(int a, int b){//Static method, swap 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 the call
exchange(i, j); //The main method can only call static methods
System.out.println("after call: " + "i=" + i + "t" + "j = " + j);//After the call
}
}
Operation results:
before call: i = 10 j = 100
after call: i = 10 j = 100
Description: when calling exchange(I, j), the actual parameters I and j respectively pass values to the corresponding formal parameters a and b. when executing the method exchange(), the change of the values of the formal parameters a and 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.
Passing a reference -- object as an argument
class Book{
String name;
private folat price;
Book(String n, float ){ //A constructor
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 the call
b.output();
b.change(b, "c++", 45.5f); //Reference passing, passing a reference to object b, changing the value of object b
System.out.print("after call:t"); //After the call
b.output();
}
}
Operation results:
before call: name:java2 price:32.5
after call: name:c++ price:45.5
Description: 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 the method change() is executed, the operation on the formal parameter a_book is the operation on the actual parameter b.