J2ME 技术的学习与实践者

[导入]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

posted on 2008-03-08 07:16 iwinyeah 阅读(52) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: