傳值---傳遞基本資料型別參數
複製代碼代碼如下:
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的操作。