JAVA,SCJP

来源:百度知道 编辑:UC知道 时间:2024/07/12 16:20:34
What does the following program do when it is run
with the following command?java Mystery Mighty Mouse
1. class Mystery {
2. public static void main(String args[]){
3. Changer c = new Changer();
4. c.method(args);
5. System.out.println(args[0] + " " + args[1]);
6. }
7. static class Changer {
8. void method(String s[]) {
9. String temp = s[0];
10. s[0] = s[1];
11. s[1] = temp;
12. }
13. }
14. }
a. The program causes and ArrayIndexOutOfBoundsException to
be thrown.
b. The program runs but does not write anything to the
standard output.
c. The program writes "Mighty Mouse" to the standard output.
d. The program writes "Mouse Mighty" to the standard output.
结果,解释

选d
因为数组作为参数传给method()方法时,传递的是数组的引用(也就是地址),不是副本。
它不象基本类型数据传参那样在内存中重新开辟空间,将值拷贝过去。
这时数组s[]和数组args[]指向同一个数组.
method(String s[])方法将s[0]与s[1]对调,就是将args[0]与args[1]对调。
因此会输出"Mouse Mightly"

d
试一下不就出来了吗