[導入]Java 初學者應對以下代碼問個為什么
網站: JavaEye 作者: iwinyeah 鏈接:http://iwinyeah.javaeye.com/blog/169280 發表時間: 2008年03月08日
聲明:本文系JavaEye網站發布的原創博客文章,未經作者書面許可,嚴禁任何網站轉載本文,否則必將追究法律責任!
public void main(){ Integer nullInt = null; tryChangeInteger(nullInt); if(nullInt == null){ System.out.println("\nThe Object nullInt not be changed."); }else{ System.out.println("\nThe Object nullInt now is " + nullInt); } } private void tryChangeInteger(Integer theInt){ theInt = new Integer(100); } // 控制臺應打印出什么呢?(The Object nullInt not be changed.) // // 關鍵要理解好Java的參數傳遞是傳值而不是傳引用,因而在tryChangeInteger方法 // 里得到的theInt不是main方法里的nullInt,而是nullInt的副本,nullInt值并沒有被改變。 // 再請看以下代碼 public void main() { char[] initChars = new char[10]; initChars[0] = 'a'; tryChangeCharArray(initChars); if(initChars[0] == 'a'){ System.out.println("\nThe Object initChars[0] not be changed."); }else{ System.out.println("\nThe Object initChars[0] now is " + initChars[0]); } } private void tryChangeCharArray(char[] theChars){ if(theChars != null && theChars.length > 0){ theChars[0] = 'b'; } } // 控制臺應打印出什么呢?(The Object initChars[0] now is b") // Why? // 弄明白了這個,JAVA引用基本就明白了。
本文的討論也很精彩,瀏覽討論>>
JavaEye推薦
文章來源:http://iwinyeah.javaeye.com/blog/169280