Friday, 5 February 2016

Call by reference and Call by value

Java uses call by value. That means all parameters to methods are pass by value or call by value,the method gets a copy of all parameter values and the method cannot modify the contents of any parameter variables that are passed to it.
Please see sample programs below.

call by value: 
class One
{
void display(int i,int j)
{
i*=4;
j/=4;
}  
}
class Two
{
public static void main(String as[])
{
int a=10;
int b=20;
System.out.println("before calling");
System.out.println("a="+a);
System.out.println("b="+b);
One sample=new One();
sample.display(a,b);
System.out.println("after calling");
System.out.println("a="+a);
System.out.println("b="+b);
}
}
OUTPUT:
before calling
a=10
b=20
after calling
a=10
b=20

call by reference:
class One
{
int a,b;
One(int i,int j)
{
a=i;
b=j;
}
void display(One ab) //pass an object
{
ab.a*=2;
ab.b/=2;
}
}

class Two
{
public static void main(String as[])
{
One sample=new One(10,20);
System.out.println("before calling");
System.out.println("a="+sample.a);
System.out.println("b="+sample.b);
sample.display(ab);
System.out.println("after calling");
System.out.println("a="+sample.a);
System.out.println("b="+sample.b);
}
}

Output:
before calling
a=10
b=20
after calling
a=20
b=10

By above example programs hope understood the difference between call by value and call by reference.


No comments :

Post a Comment