Java中傳值和傳引用
阿新 • • 發佈:2019-02-11
原理:對於基本型別的變數,Java中時傳的值的副本,而對於一切的物件型變數,Java都是傳引用的副本。
程式碼示例:
import java.util.*; public class Test{ public static void main(String[] args) { StringBuffer str = new StringBuffer("hello"); test(str); System.out.println(str); } public static void test(StringBuffer str) { str.append(",world!") ; } }
執行結果:
c:\Users\caopu\Desktop>java Test
hello,world!
StringBuffer是產生一塊記憶體空間,相關的增刪改查都在其中進行,str始終指向該物件,但是在原來的字串尾部進行追加新的字串。再看下面:
-------------------------------------------------------------------------------------------------------------
執行結果為:import java.util.*; public class Test{ public static void main(String[] args) { String string = "hello"; test(string); System.out.println(string); } public static void test(String str) { str = "abc";//該行語句實際上生成了一個新的為abc的字串 } }
c:\Users\caopu\Desktop>java Test
hello
注意:String是final型別的,不可以進行繼承和修改