java中的值传递和引用传递的区别分析
public class PassValue{
static void exchange(int a, int b){//静态方法,交换a,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);//调用前
exchange(i, j); //值传递,main方法只能调用静态方法
System.out.println("after call: " + "i=" + i + "\t" + "j = " + j);//调用后
}
}
before call: i = 10 j = 100
after call: i = 10 j = 100
说明:调用exchange(i, j)时,实际参数i,j分别把值传递给相应的形式参数a,b,在执行方法exchange()时,形式参数a,b的值的改变不影响实际参数i和j的值,i和j的值在调用前后并没改变。
引用传递---对象作为参数
代码如下:
class Book{
String name;
private folat price;
Book(String n, float ){ //构造方法
name = n;
price = p;
}
static void change(Book a_book, String n, float p){ //静态方法,对象作为参数
a_book.name = n;
a_book.price = p;
}
public void output(){ //实例方法,输出对象信息
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"); //调用前
b.output();
b.change(b, "c++", 45.5f); //引用传递,传递对象b的引用,修改对象b的值
System.out.print("after call:\t"); //调用后
b.output();
}
}
before call: name:java2 price:32.5
after call: name:c++ price:45.5
说明:调用change(b,"c++",45.5f)时,对象b作为实际参数,把引用传递给相应的形式参数a_book,实际上a_book也指向同一个对象,即该对象有两个引用名:b和a_book。在执行方法change()时,对形式参数a_book操作就是对实际参数b的操作。