Showing posts with label call by value. Show all posts
Showing posts with label call by value. Show all posts

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.


Monday 20 January 2014

A CLOSER LOOK AT ARGUMENT PASSING

There are two ways that a computer language can pass an argument to a subroutine. The first way is call-by-value.This method copies the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument. The second way an argument can be passed is call-by-reference. In Java, when you pass a simple type to a method, it is passed by value. Thus, what occurs to the parameter that receives the argument has no effect outside the method.