java中的值傳遞和引用傳遞的區別分析

來源:互聯網
上載者:User

傳值---傳遞基礎資料型別 (Elementary Data Type)參數

複製代碼 代碼如下: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的操作。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.