面试题-值传递 & 引用传递
以下程序的输出结果是?
1 public class Example {
2 String str = new String("good");
3 char[] ch = { 'a', 'b', 'c' };
4
5 public static void main(String args[]) {
6 Example ex = new Example();
7 ex.change(ex.str, ex.ch);
8 System.out.print(ex.str + " and ");
9 System.out.print(ex.ch);
10 }
11
12 public void change(String str, char ch[])
13 {
14 str = "test ok";
15 ch[0] = 'g';
16 }
17 }
正确答案: B
A 、 good and abc
B 、 good and gbc
C 、 test ok and abc
D 、 test ok and gbc
解析:
考察值传递和引用传递。对于值传递,拷贝的值用完之后就会被释放,对原值没有任何影响,但是对于引用传递,拷贝的是对象的引用,和原值指向的同一块地址,即操作的是同一个对象,所以操作之间会相互影响
所以对于String str是值传递,操作之间互不影响,原值保持不变。而ch是数组,拷贝的是对象的引用,值发生了改变,因此选择B
posted on 2017-07-07 11:56 alex5211314 阅读(218) 评论(0) 收藏 举报

浙公网安备 33010602011771号