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引用基本就明白了。
评论
ggweixudong 2008-08-14
~呵呵,测试了下你的留言版,不太行哦!~~~
ggweixudong 2008-08-14
  1. [list=1]
  2. [*][list=1]
  3. [*][*][list=1]
  4. [*][*][*][list=1]
  5. [*][*][*][*][list=1]
  6. [*][*][*][*][*][list=1]
  7. [*][*][*][*][*][*][list=1]
  8. [*][*][*][*][*][*][*][list=1]
  9. [*][*][*][*][*][*][*][*][b][b]gewfewafewa[/b][/b]
  10. [*][*][*][*][*][*][*]
  • [*][*][*][*][*][*][/list]
  • [*][*][*][*][*][/list]
  • [*][*][*][*][/list]
  • [*][*][*][/list]
  • [*][*][/list]
  • [*][/list]
  • [/list]
  • [/list]
    iwinyeah 2008-03-09
    我认为http://blog.csdn.net/hdwt/archive/2006/12/28/1465447.aspx文出彩的地方是将引用比喻成遥控器,大家都是遥控同一台电视,别人(在方法内)调了成体育频道,你(方法调用者)只能看体育频道了,除非你再调回来.
    iwinyeah 2008-03-09
    关于这个问题网上争论也较多,参看http://blog.csdn.net/hdwt/archive/2006/12/28/1465447.aspx我认为他讲得也比较好.

    不过个人认为对这个问题寻根问底的话,就会回到JAVA的基础知识:java对数据类型的规定,在Java中,对象实体和数组(其实数组也是对象)是使用引用来表达的,而基础数据类型则是没有引用的(它们无须另外分配空间).

    理解了这个,就会明白"无论在什么情况下,Java参数传递方式都是传值"这句话了.
    在传递基础类型变量的时候,它在栈中生成该变量的副本,方法改变的是副本的值,因此并不影响原变量本身.
    在传递对象实体变量的时候,它在栈中生成的也是该变量的副本,这时候,方法可能有两种行为:
    // 1: 改变变量的副本本身
    // 不影响原变量(它所引用的对象实体还是原来的对象实体)
    private void changeSelf(Student theStudent){
        theStudent = new Student(1,"Alexander");
    }
    
    // 2: 改变变量所引用的对象实体
    // 不影响原变量(它所引用的对象实体还是原来的对象实体,但该对对象实体的属性被改变了),
    private void changeReference(Student theStudent){
        theStudent.id = 2;
    }
    
    zhjb7 2008-03-08
    传的是引用的地址。
    调用方法后,实际上是新建了一个引用,但这个新的引用地址和原来的引用地址一样,这样第一题实际上是新建了一个对象并把地址给了新建的引用,而原来的引用地址并没改变,所以还是NULL。第二题是新建了一个数组,原来的数组引用地址和这个新建数组的地址是一样的,所以这个新建数组改变了,原来的数组也就改变了。
    不知道我回答的对不对?
    ggggqqqqihc 2008-03-08
    貌似没什么玄机,不过问题还是不错的。
    发表评论

    您还没有登录,请登录后发表评论

    iwinyeah
    搜索本博客
    我的相册
    C8609f76-ccc2-3dbc-a9e8-b5e08077b8c2-thumb
    jaccount1.0.7
    共 5 张
    最近加入圈子
    存档
    最新评论