今天网上碰到了题测试题: 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 "); 
    Sytem.out.print(ex.ch);   }  
 public void change(String str,char ch[])
{    
 str="test ok";  
   ch[0]=`g`;  
 } 
执行的结果是: good and gbc
原因是
字符串是不可修改的,而char[]这个数组的内容是可以修改的。
我运行了下,确实是这样的结果,但是我用另外个类似的类:
public class a
{
static String m=new String("ada");
public static void main(String args[])
{

m="eeeee";
System.out.println(m);
}}运行结果却是:eeeee
为什么会这样呢?不是说字符串不可修改吗?怎么这里又可以修改了?请高人回答!

解决方案 »

  1.   

    m是一个引用 "ada"和"eeee"都是放在常量池的字符串;你的一次m引用的是String对象的地址,第二次m是引用"eeee"的地址,而"ada"和"eeee "在常量池里是没变的。
      

  2.   

    这里并没有修改字符串中的内容,
    m 是引用类型,本来指向"ada",
    执行m="eeeee"; 之后m指向的内容变成了"eeeee",但是本来的"ada"还是存在于内存中
      

  3.   

    那第一个例题中的str不也是个应用么?为什么他不能通过方法改变?
      

  4.   

    你在public void change(String str,char ch[]) 是在change里重新new 了一个新的String 对象,里把那个形参str的值给该了,又不是该得
    外部声明的str
    public class Example{   
     String str=new String("good"); 
      char[]ch={`a`,`b`,`c`};   
     public static void main(String args[]){   
       Example ex=new Example();   
       ex.str=ex.change(ex.str,ex.ch);     
     System.out.print(ex.str+" and "); 
        Sytem.out.print(ex.ch);   }   
     public String change(String str,char ch[]) 
    {     
     str="test ok";   
       ch[0]=`g`;  
          return str;
     } 结果应该是test ok and gbc 
      

  5.   

    那个程序时我直接复制的LZ的,然后直接该得,很定不能运行,Sytem.out.print(ex.ch);   直接输出数组的引用,也没重写toString
      

  6.   

    public class Example {
    String str = "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[]) {
    this.str = "test ok";
    ch[0] = 'g';
    }
    }