Tuesday, December 13, 2011

What is call-by-value and call-by-reference in java?

Call by Value:
When we pass a variable of int, float or any other type of data to a method or some constant values like sample(5,10), they are all passed by value. A copy of variable’s value is passed to the receiving method and hence any changes made to the values do not affect the actual variables.
Example:
class call_by_val
{
int n1,n2;
public void get(int x,int y)
{
x=x*x; //Changing the values of passed arguments
y=y*y; //Changing the values of passed arguments
}
}
class test
{
public static void main(String args[])
{
int a,b;
a=5;
b=10;
System.out.println("Initial Values of a & b "+a+" "+b);
call_by_val obj=new call_by_val();
obj.get(a,b);
System.out.println("Final Values "+a+" "+b);
}
}
output:
Initial Values of a & b 5 10
Final Values 5 10

Call by Reference:
Objects are always passed by reference. When we pass a value by reference, the reference or the memory address of the variables is passed. Thus any changes made to the argument causes a change in the values which we pass.
Example:
class call_by_ref
{
int n1,n2;
public void get(int a,int b)
{
n1=a;
n2=b;
}
public void doubleit(call_by_ref temp)
{
temp.n1=temp.n1*2;
temp.n2=temp.n2*2;
}
}
class test
{
public static void main(String args[])
{
int x=5,y=10;
call_by_ref obj=new call_by_ref();
obj.get(x,y); //Pass by Value
System.out.println("Initial Values are: ");
System.out.println(+obj.n1);
System.out.println(+obj.n2);
obj.doubleit(obj); //Pass by Reference
System.out.println("Final Values are:");
System.out.println(+obj.n1);
System.out.println(+obj.n2);
}
}
output:
Initial Values are:
5
10
Final Values are:
10
20