您的位置:首页 > 其它

值传递 & 引用传递

2016-05-02 20:02 260 查看
以下程序的输出结果是?

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';
}
}


正确答案: B

A 、 good and abc


B 、 good and gbc


C 、 test ok and abc


D 、 test ok and gbc

解析:

考察值传递和引用传递。对于值传递,拷贝的值用完之后就会被释放,对原值没有任何影响,但是对于引用传递,拷贝的是对象的引用,和原值指向的同一块地址,即操作的是同一个对象,所以操作之间会相互影响
所以对于String str是值传递,操作之间互不影响,原值保持不变。而ch是数组,拷贝的是对象的引用,值发生了改变,因此选择B
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: