[转]Does Java pass by reference or pass by value?
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
Does Java pass by reference or pass by value?
Why can't you swap in Java?
By Tony
Sintes, JavaWorld.com, 05/26/00
Print
Email
Feedback
Resources
Discuss
(76)
Digg
Reddit
SlashDot
Stumble
del.icio.us
Technorati
dzone
If Java uses the pass-by reference, why
won't a swap function work?
Your question demonstrates a common error made by
Java language newcomers. Indeed, even seasoned veterans find it
difficult
to keep the terms straight.
Java does manipulate objects by reference, and
all object variables are references. However, Java doesn't pass method
arguments
by reference; it passes them by value.
Take the badSwap()
method for
example:
public void badSwap(int var1, int var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
}
When badSwap()
returns, the
variables passed as arguments will still hold their original values. The
method will also fail if we change
the arguments type from int
to Object
,
since Java passes object references by value as well. Now, here is
where it gets tricky:
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
If we execute this main()
method,
we see the following ou
相关文档:
JAVA是一种编程语言,一种开发环境,一种应用环境,一种部署环境,一种广泛使用的网络编程语言,它是一种计算概念。
组成Java的3个分支:
J2SE(Java 2 Platform Standard Edition):Java标准版,包含构成JAVA语言核心 ......
最近经常和公司做JAVA的兄弟们打交道,由于需要统加密算法,所以要求做一个加密的DLL文件供兄弟们调用,根据网上各位大虾们的经验,在加上个人在摸索过程中的体会,现在将流程以及个人心得贴上,以供以后漫漫程序生涯参考,如有不对的还请各位大力指正。
第一步是编写java类, ......
因数据安全,需要将生成的报表xls,添加水印,所以自已在jxl中进行代码修改。
使用例子
public class testJxl {
public static void main(String[] args) throws Exception {
OutputStream out = new FileOutputStream("./aaaa.xls"); // 写入到FileInputStream
WritableWorkbook wwb= Workbook.createWorkbook(out);
......
在传智的这段时间每天的情形想都想得到,两点一线,但是每天都感觉到很充实,学习,不停的学习。越是不停的学习,越是感觉自己的力量是那么的微薄,自己的能力是那么的小,JAVA真是博大精深。老师说叫我们不要担心,可是我不担心也不可能哦,毕竟在同类学校毕业的,也许我们可以算得上是很不错的,但是和我们同台竞技的人 ......
0. 学习一章掌握一张,然后再不断的用。
1. 找一些比较经典的例子,源码(源码爱好者), 每个例子比较集中一种编程思想而设计的,比如在我的实践当中,我曾经学习过一个很经 典的例子就是用Java实现的HotDraw(源自SmallTalk),你可以用rolemodel或hotdraw在 搜索引擎上找一下,我记不大清 ......