[转]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
相关文档:
1. 分页的解决方案,通用性,分页时参数丢失问题,如何解决?
2. Hibernate优化问题。如何优化数据库访问,使程序访问数据库更优化。
初用HIBERNATE的人也许都遇到过性能问题,实现 ......
1. 对自己的总结和理解的升华是我喜欢做的一件事,在实际项目过程中,很多地方都用到动态生成树形菜单的地方,现在就给大家讲讲如何动态生成一棵树。
2. 首先我们必须要建立树的节点模型,其实树的节点模型中往往就是我们需要存放的数据对象,很 ......
步骤一:(打包class文件)
在命令行中执行以下的语句:jar -cvf
MyApplet.jar class
注意这里的所有.class文件均是放在一个class的目录中的。本步骤执行完毕后,将在
c:/admin中产生一个名为MyApplet.jar的文件
步骤二:(在网页中嵌入Applet)
这个网页的名字叫做FileReaderApplet.html, ......
8. 当系统处理完成后,报表被显示出来。这是一份商品销售报告,显示的是每类商品的季度销售额以及累计情况。接下来,我们尝试用 Java
创建一个事件响应处理类,把每季度销售额在10万美元以上的数据用红色标示出来。
创建 Java 类
按照如下步骤,用 Java 创建百灵报表(BIRT)的事件响应处理程序。
......