值傳遞 & 引用傳遞

如下程序的輸出結果是?數組

 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
相關文章
相關標籤/搜索