Wednesday, October 5, 2011

There is no call by reference in Java....

The Myth: Primitive types are called by value and Objects are passed by reference in Java.
The Truth: There is no call by reference in Java.
let's see one example:

class Democall
{int ival1=2,ival2=3;
int fun1 (int a, int b) { a=a*2; b=b*2; return(a+b); }

int fun2 (Democall obj) { obj.ival1=obj.ival1*2; obj.ival2=obj.ival2*2; return(obj.ival1+obj.ival2);}

public static void main(String args[])
{
int i=2,j=3;
Democall obj1=new Democall();//new object creation
int k=obj1.fun1(i,j);//passing i,j values to fun1's a,b
System.out.println(i+" "+j+" "+k);
k=obj1.fun2(obj1);//passing value of object obj1 to the fun2's obj
System.out.println(obj1.ival1+" "+obj1.ival2+" "+k);
}
}
output:
2 3 10
4 6 10

Now you might say: yes it is call by reference as second output is indeed changing the values of object.
But the truth lies in the memory operations of java. The function fun1 is totally fine as it is working with primitive types and indeed its is well known as call by value, but in fun2 the obj is itself passed on to the function fun2, so the value of obj1 has to be copied in to obj. Now just think what could be the value of obj1, will it not be the address of the newly created object? So the address of new Democall() is acting as the value for obj1 which would be passed as value to obj, now if obj accesses data member ival1 and ival2 it would be obviously obj1's ival1 and ival2 which ultimately got reflected in main function.
So it will give you a look and feel of a pass by reference but in the actual working it is call by value.

No comments:

Post a Comment