Sunday, March 20, 2011

What is Call by Value & Call by Reference in Java-Swap Example-Java Interview Queston

Call By Value

Definition: It is a type of function call wherein the argument passed is of a primitive data type and the value of the argument gets copied to the parameter of the function and in the function definition even if we are swapping the values of the parameter we are actually swapping the copies of the argument not the actual argument.

Example
public class Test
{
int x=10;
int y=20;
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
}
public class TestMain
{
public static void main(String[] args)
{
A obj=new A();
int t=10;
int s=20;
obj.swap(t, s);
System.out.println(t+" "+s);// The argument value remains the same
//it is not changed.
}
}
view raw TestMain.java hosted with ❤ by GitHub



Call By Reference 

Definition: The argument passed in this type of function is an object type and not a primitive data type. Using call by reference the modifications can be done on the actual arguments because the references of the arguments are passed during the function call. 

Example
public class Test
{
int i,j; //Instance variables for Class Test
void swap_ref(Test a, Test b)
{
int temp;
temp = a.i;
a.i = b.i;
b.i = temp;
temp = a.j;
a.j = b.j;
b.j = temp;
}
}
public class TestMain
{
public static void main(String[] args)
{
Test t2 = new Test();
Test t3 = new Test();
t2.i= 10; //Initialising the instance value of class Test with objects t2 and t3
t2.j = 20;
t3.i = 5;
t3.j = 7;
t1.swap_ref(t2, t3);
}
}
view raw TestMain.java hosted with ❤ by GitHub


For details regarding Online Java J2ee Training please visit www.javatutoronline.com