| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 769 人关注过本帖
标题:一道方法调用的笔试题
只看楼主 加入收藏
西鄙人
Rank: 2
等 级:论坛游民
帖 子:36
专家分:12
注 册:2009-12-2
结帖率:100%
收藏
 问题点数:0 回复次数:6 
一道方法调用的笔试题
public static void main(String[] args){
    String str=new String("hello");
    char[] c=new char[]{'a','b','c'};
    method(str,c);
    System.out.println("str="+str+" ***** c="+(new String(c)));
}

public static void method(String str,char[] c){
    str="ok there";
    c[0]='g';
}

没有ide,用记事本编辑的,可能有错误,各位谅解。大致意思应该表达清楚了。
问以上程序输出结果是什么?

本人想不太明白,望高手解释。

[ 本帖最后由 西鄙人 于 2010-11-8 21:41 编辑 ]
搜索更多相关主题的帖子: 笔试 
2010-11-08 14:44
linjx0123
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:14
帖 子:279
专家分:1362
注 册:2006-4-7
收藏
得分:0 
应该是hello ***** gbc吧。
因为method的str 和c相当于String str1 = str; char[] c1 = c;然后str1 = "ok there", c1[0]='g';
所以str1指向了"ok there",而str还是指向"hello",而c1跟c指向同一块内存,所以c[0]='g'
2010-11-08 23:32
西鄙人
Rank: 2
等 级:论坛游民
帖 子:36
专家分:12
注 册:2009-12-2
收藏
得分:0 
回复 2楼 linjx0123
str1和c1都是引用,为何str1改变了引用,而c1改变的是内容呢?跪求。
2010-11-09 10:42
linjx0123
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:14
帖 子:279
专家分:1362
注 册:2006-4-7
收藏
得分:0 
不是引用。。。。。。
程序代码:
public static void main(String[] args){
        String str=new String("hello");
        char[] c=new char[]{'a','b','c'};
       
        //method(str,c);这个方法其实相当于以下4行代码
        String str1 = str;
        str1 = "ok there";
        char[] c1 = c;
        c1[0] = 'g';
       
        System.out.println("str="+str+" ***** c="+(new String(c)));
    }

 
2010-11-09 12:35
linjx0123
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:14
帖 子:279
专家分:1362
注 册:2006-4-7
收藏
得分:0 
画图表示的话,就是
String str=new String("hello"): str -> "hello"
method(str,c) : str1 -> "hello"
method(str,c)方法里是 : str1 -> "ok there"。
所以最终是str -> "hello"  str1 -> "ok there"
 
而另外一个是
char[] c=new char[]{'a','b','c'} : c -> {'a','b','c'}
method(str,c) : c1 -> {'a','b','c'}
method(str,c)方法里是 : c1[0]='g', 也就是把{'a','b','c'}的第一个赋值为g, 所以内存中变成{'g','b','c'}.
最终结果是 c -> {'a','b','c'},  c1 -> {'a','b','c'}

假如method方法修改下:
public static void method(String str,char[] c){
    str="ok there";
    c = new char[]{'h','i'};
}
那么输出后System.out.println(new String(c))的结果就是abc了


2010-11-09 12:45
西鄙人
Rank: 2
等 级:论坛游民
帖 子:36
专家分:12
注 册:2009-12-2
收藏
得分:0 
回复 5楼 linjx0123
感谢感谢!
char[] c1理解起来合理。但String类型理解就不容易了。
本人愚钝,可以理解为String类型是固定的字符串,如果改变就需要改变引用,所以str1的引用改变了,但str指向“hello”的引用没有改变,所以str输出还是hello
2010-11-10 11:31
zybjava
该用户已被删除
收藏
得分:0 
提示: 作者被禁止或删除 内容自动屏蔽
2010-11-14 11:03
快速回复:一道方法调用的笔试题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.025050 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved