Sunday, January 28, 2007

Passing objects into Methods in Java

Having worked with C/C++ extensively for couple of year, now I am refreshing my memory on Java..It's kinda difficult to do away with C/C++ practices :) Thought the following post might be of interest to you.

Is parameter passing in Java by reference or by value?
Bottomline: Everything in java is passed by value. But objects are NEVER passed to the method!

myth: objects are passed by reference, primitives are passed by value. (This is wrong)

Pass by reference means, you are working with the actual pointer that points to the object. For example, this is how C++ works.


When java passes an object to a method, it first makes a copy of a reference to the object, not a copy of the object itself.

The following example illustrates the point.

public class PassByValueTest {

class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}

public void setPoint(int x, int y) {
this.x = x;
this.y = y;
}

public String toString() {
return "Point[x="+x+",y="+y+"]";
}
}

public void method1(Point pt){
pt.setPoint(5, 5);
}

public void method2(Point pt){
pt = new Point(10,10);
}

public Point createPoint(){
return new Point(1,1);
}


public static void main(String [] args){
PassByValueTest test = new PassByValueTest();
Point p = test.createPoint();
System.out.println("Before calling method1: "+ p.toString());
strTest.method1(p);
System.out.println("After calling method1: "+ p.toString());
strTest.method2(p);
System.out.println("After calling method2: "+ p.toString());
}

Output:
Before calling method1: Point[x=1,y=1]
After calling method1: Point[x=5,y=5]
After calling method2: Point[x=5,y=5]

Notice that values inside the Point object get changed after calling method1, but not after method2. That's becasue, a copy of a reference to Point object p is passed, not the actual refernce itself. This is the key difference from languages like C++.

ref1(address) ---> p (object) <--- copyref1(address)

copyref1 is passed into method1. We modify the object pointed to by copyref1 which is the actual object. Therefore the mofications remain even after calling method1.

copyref1 is passed into method2. When our code gets out of method2, it does not affect the object pointed to by ref1. The new object created inside method2 simply garbage collected by the JVM.

Futher reading:
http://www.yoda.arachsys.com/java/passing.html
http://www-128.ibm.com/developerworks/library/j-praxis/pr1.html
http://javadude.com/articles/passbyvalue.htm

1 comment:

Anonymous said...

good explanation...