Java的方法參數(shù)是按值傳遞的
基本類(lèi)型傳遞的是字面值,引用類(lèi)型傳遞的是地址值布蔗。
也可以理解成藤违,基本類(lèi)型按值傳遞浪腐,引用類(lèi)型按引用傳遞纵揍。
為什么
例子:
- 例1
@Test
public void testPara1() {
int a = 100, b;
b = modBaseType(a);
System.out.println(a); // 100
System.out.println(b); // 101
}
int modBaseType(int n) {
n += 1;
return n;
}
- 例2
@Test
public void testPara2() {
int[] a = { 1, 2, 3, 4 }, na;
na = modArray(a);
printArray(a); // 2018 2018 2018 2018
printArray(na); //2018 2018 2018 2018
}
void printArray(int[] array) {
for (int item : array) {
System.out.print(item + " ");
}
System.out.println();
}
int[] modArray(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = 2018;
}
return array;
}
- 例3
@Test
public void testPara3() {
ClassWithMutableProperty c = new ClassWithMutableProperty(),nc;
nc=modCWMP(c);
System.out.println(c.getN()); // 1000
System.out.println(nc.getN()); // 1000
}
ClassWithMutableProperty modCWMP(ClassWithMutableProperty obj) {
obj.setN(1000);
return obj;
}
- 例4
@Test
public void testPara4() {
String s = "hello", ns;
ns = modS(s);
System.out.println(s); // hello
System.out.println(ns); // helloworld
}
String modS(String s) {
return s += "world";
}
上面四個(gè)例子,實(shí)際上是三類(lèi)议街,1是基本數(shù)據(jù)類(lèi)型泽谨,2,3是對(duì)象本身提供了修改自己屬性的方法,4是對(duì)象未提供修改自身的方法特漩。
在例1中吧雹,實(shí)參把數(shù)值傳給形參,之后便再無(wú)瓜葛涂身。
例2和3以及例4中雄卷,實(shí)參把對(duì)象的地址傳給形參,變成以下這樣:
參數(shù)傳遞
如果對(duì)象本身可變,那對(duì)其作出的更改操作都將反映到實(shí)參和形參上蛤售,因?yàn)樗麄冎赶蛲粋€(gè)地址丁鹉。