代碼:
public class TestString {
String str = new String("good");
char [] ch = {'a','b','c'};
public static void main(String[] args) {
// TODO Auto-generated method stub
TestString ex = new TestString();
ex.change(ex.str,ex.ch);
System.out.println(ex.str+"and");
System.out.println(ex.ch);
}
public void change(String str2, char[] ch2) {
System.out.println("交換前:" + str2);
//result is the same
//str2 = new String("test ok");
str2 = "test ok";
System.out.println("交換后:" + str2);
ch[0] = 'g';
}
}
輸出結果:
交換前:good
交換后:test ok
goodand
gbc
分析:因為String類是一個不可變類型,從變量被聲明時,內存大小已經固定了,如果要改變它的值,會重新開辟新的內存存儲,所以輸出的str還是初始化的那個,即String類型作為方法的形參並不會改變字符串內容。
