经典指数          
原因
7044
浏览数
1
收藏数
 

以下程序的输出结果是?
public class Example {
    String str = new String("good");
    char[] ch = { 'a', 'b', 'c' };

    public static void main(String args[]) {
        Example ex = new Example();
        ex.change(ex.str, ex.ch);
        System.out.print(ex.str + " and ");
        System.out.print(ex.ch);
    }

   public void change(String str, char ch[])       
   {
        str = "test ok";
        ch[0] = 'g';
    }
}
  • good and abc
  • good and gbc
  • test ok and abc
  • test ok and gbc

     举报   纠错  
 
切换
1 个答案

其实都是引用传递,只是因为String是个特殊的final类,所以每次对String的更改都会重新创建内存地址并存储(也可能是在字符串常量池中创建内存地址并存入对应的字符串内容),但是因为这里String是作为参数传递的,在方法体内会产生新的字符串而不会对方法体外的字符串产生影响。

 
切换
撰写答案