1. 程式人生 > >java中傳值還是傳引用

java中傳值還是傳引用

不管java引數的型別是什麼,一律傳遞引數的副本。如果java是值傳遞,那麼傳遞的是值的副本;如果是傳引用,那麼傳遞的是引用的副本。在java中,變數分為以下兩類:①對於基本型別(int、double、float、byte、boolean、char),java是傳值的副本;②對於一切物件型變數,java都是傳引用的副本,其實傳引用的副本的實質就是複製指向地址的指標。

public class Test {
public static void main(String[] args) {
boolean test = true;
System.out.println("Before test:" + test);
test(test);
System.out.println("After test:" + test);
}


public static void test(boolean test) {
test = !test;
System.out.println("In Test:" + test);
}
}

執行結果為:

Before test:true
In Test:false
After test:true

由以上可知,雖然test(boolean)方法中改變了傳進來的引數值,但是對這個引數源變數本身並沒有影響,說明引數型別是簡單型別的時候,是按值傳遞的。是把引數的值作為一個副本傳進方法函式的,那麼在方法函式中不管怎麼改變其值,都只是改變了副本的值,而不是源值。

public class Test {
public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer("Hello");
test(stringBuffer);
System.out.println(stringBuffer);
}


public static void test(StringBuffer str) {
str.append(",World");
}
}

執行結果為:

Hello,World

test(stringBuffer)呼叫了test(StringBuffer)方法,並將stringBuffer作為引數傳遞了進去。這是stringBuffer是一個引用,java對於引用形式傳遞物件型別的變數時,實際上是將引用作為一個副本傳進方法函式的。這個函式裡面的引用副本指向的是物件的地址。通過副本找到了地址,並修改了地址中的值。