1 public class ch01 { 2 String str = "lisi"; 3 public static void change(String str){ 4 System.out.println(str); 5 } 6 7 public static void main(String[] args) { 8 ch01 c = new ch01(); 9 String str01 = "zhangsan"; 10 change(str01); 11 System.out.println(c.str); 12 } 13 }
輸出結果爲:spa
zhangsan
lisicode
分析:由於String是個特殊的final類,因此每次對String的更改都會從新建立內存地址並存儲(也多是在字符串常量池中建立內存地址並存入對應的字符串內容),可是由於這裏String是做爲參數傳遞的,在方法體內會產生新的字符串而不會對方法體外的字符串產生影響。blog
另外內存
1 public class Example { 2 String str = new String("good"); 3 char[] ch = { 'a', 'b', 'c' }; 4 5 public static void main(String args[]) { 6 Example ex = new Example(); 7 ex.change(ex.str, ex.ch); 8 System.out.print(ex.str + " and "); 9 System.out.print(ex.ch); 10 } 11 12 public static void change(String str, char ch[]) 13 { 14 str = "test ok"; 15 ch[0] = 'g'; 16 } 17 }
此段代碼的輸出結果是:字符串
good and gbc
1 public class Example{ 2 String str=new String("hello"); 3 char[]ch={'a','b'}; 4 public static void main(String args[]){ 5 Example ex=new Example(); 6 ex.change(ex.str,ex.ch); 7 System.out.print(ex.str+" and "); 8 System.out.print(ex.ch); 9 } 10 public void change(String str,char ch[]){ 11 str="test ok"; 12 ch[0]='c'; 13 } 14 }
此段代碼的輸出結果爲class
hello and cb