值傳遞,是指方法調用時,傳遞的參數是按值的拷貝傳遞。java
如:
shell
public class ValueTest { public void test(int x){ System.out.println("值傳遞,x:"+x); } public static void main(String[] args) { int x = 1; new ValueTest().test(x); } }
引用傳遞,是指方法調用時,傳遞的參數是按引用進行傳遞,其實傳遞的引用的地址,也就是變量所對應的內存空間的地址。ide
如:this
public class ReferenceTest { public void test(Rf rf) { System.out.println("引用傳遞,rf:" + rf); } public static void main(String[] args) { Rf rf = new Rf(1, "張三"); new ReferenceTest().test(rf); } } class Rf { private int id; private String name; public Rf() { } public Rf(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "id:" + id + ",name:" + name; } }
值傳遞後,改變傳遞參數,因爲是拷貝一份,參數不會改變
spa
引用傳遞後,改變傳遞參數,引用是同一個對象,參數會改變code
例子:orm
public class ReferenceAndValueTest { public void test1(int x) { System.out.println("獲取到,x:" + x); x++; System.out.println("改變爲,x:" + x); } public void test2(String str) { System.out.println("獲取到,str:" + str); str = "李四"; System.out.println("改變爲,str:" + str); } public void test3(Rf rf) { System.out.println("獲取到,rf:" + rf); rf.setName("李四"); System.out.println("改變爲,rf:" + rf); } public static void main(String[] args) { ReferenceAndValueTest vat = new ReferenceAndValueTest(); int x = 1; System.out.println("調用前,x;" + x); vat.test1(x); System.out.println("調用後,x;" + x); String str = "張三"; System.out.println("調用前,str;" + str); vat.test2(str); System.out.println("調用後,str;" + str); Rf rf = new Rf(1, "張三"); System.out.println("調用前,rf:" + rf); vat.test3(rf); System.out.println("調用後,rf:" + rf); } } class Rf { private int id; private String name; public Rf() { } public Rf(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "id:" + id + ",name:" + name; } }
執行結果:對象
調用前,x;1 獲取到,x:1 改變爲,x:2 調用後,x;1 調用前,str;張三 獲取到,str:張三 改變爲,str:李四 調用後,str;張三 調用前,rf:id:1,name:張三 獲取到,rf:id:1,name:張三 改變爲,rf:id:1,name:李四 調用後,rf:id:1,name:李四
解釋:內存
經過執行結果:(int)x 是值傳遞,(String)str 是值傳遞,(Rf對象)rf 是引用傳遞get
Java中基本數據類型是以值傳遞的方式進行傳參;
對象類型是以引用傳遞的方式進行傳參;
String類型不屬於基本數據類型,可是以值傳遞的方式進行傳參;