A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© mf152 中级黑马   /  2013-9-18 17:22  /  1406 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 杨增坤 于 2013-9-22 21:01 编辑

这段程序的打印为什么是:good and gbc  是怎么推的?
    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';
  }
}

6 个回复

倒序浏览
通过new String()与str="test ok"是2个不一样的内存块,所以,你在change()函数中只是重新在内存中开辟了一块临时内存存放“test ok”,并未改变str=new String()《这个是存在与堆内存中的》中str的值,而ch不同,你通过ch[0]改变的实际就是在Example类中创建的那个ch,string是一个特殊的对象
回复 使用道具 举报
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"; //实际上重新在栈内存中开辟了一片内存  值为“test ok”并将他赋给str,这里的str与上面的new String()的对象引用变量的str是不一样的    
        ch[0]='g'; //这里的ch与上面的ch都是指向同一堆内存地址
  }
}

评分

参与人数 1技术分 +1 收起 理由
EYE_SEE_YOU + 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 ");
    Sytem.out.print(ex.ch);
  }
  public void change(String str,char ch[]){
    str="test ok";  
         ch[0]='g';
  }
}

对象 数组  都是在堆内存中,变量 是在栈内存中,   String str=new String("good");
  char[]ch={'a','b','c'}; 这两个都保留在了堆内存中, str="test ok";  保存在栈内存中,当花括号结束就释放内存。      ch[0]='g'; 保存在堆内存中,他把 char[]ch={'a','b','c'};地址为0的第一号元素‘a’给替换了,变成了ch={'g','b','c'}。    记住:栈内存是在方法花括号结束释放内存,堆内存随着内的加载完毕花括号才释放内存。   现在理解了吗?

评分

参与人数 1技术分 +1 收起 理由
杨增坤 + 1

查看全部评分

回复 使用道具 举报
恩  谢谢
回复 使用道具 举报

    分析如下见注释:不知道有没有问题,
  1. public class Example{
  2.   String str=new String("good");
  3.   char[]ch={'a','b','c'};
  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.     Sytem.out.print(ex.ch);
  9.   }
  10.   public void change(String str,char ch[]){
  11.     str="test ok"; //这里改变了str的数据,让str指向“test ok ”的地址,但没有改变str原有数据
  12.     ch[0]='g'; //这里改名零号位的数据为g.
  13.   }
  14. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
杨增坤 + 1

查看全部评分

回复 使用道具 举报
字符串一旦被创建就不能被改变,你在下面的代码是重新创建了一个字符串对象,所以原来的字符串根本没有改变!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马