对于笔试题--“good and abc”的理解

今天朋友问了一个面试题,题目如下:

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 ,为啥 str没改变而ch 改变了呢??

   

   下面将粗略画一下程序执行过程中JVM中内存情况,来解释为什么为啥 str没改变而ch 改变了

   执行Example ex=new Example();  后没有执行方法change之前的内存情况如图:

在执行ex.change(ex.str,ex.ch)后,没有执行 str="test ok"之前时内存情况如下:
 
在执行完change方法中ch[0]='g'后,方法没有退出之前,内存情况如下:   
原因已经很明显了。
以上都是个人对程序的理解,如有不对之处请轻喷。。。。
posted @ 2016-04-05 12:53  红色十字军  阅读(1688)  评论(0)    收藏  举报