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