Saturday 2 March 2013

Argument Passing in java


Arguments passed to a sub-routine (method) is falls into two categories.    
  1.         Call by value
  2.         Call by reference



1. Call by Value: Call by value copies the value of an argument into the formal parameter of the sub-routine.  Therefore, if changes made to the parameter of the sub-routine have no effect on the argument used to call it.

Example:

class Test
{
            void meth(int i, int j)
            {
            i*=2;
            j/=2;
            }
}
class cbv
{
            public static void main(String[] args)
            {
            Test obj=new Test();
            int a=4,b=7;
            System.out.println("Before calling a="+a+" b="+b);
            obj.meth(a,b);
            System.out.println("After  calling a="+a+" b="+b);
            }
}

O/P:    Before calling a=4 b=7
            After    calling a=4 b=7



2. Call by Reference: In this method, a reference to an argument is passed to the parameter.  Inside the parameter, this reference is used to access the actual argument specified in the call.  Therefore, any changes made to the parameter will effect the argument used to call it.  This one is also referred as passing an object as parameter to a method.


Example:

class Test
{
            int a,b;
            Test(int i,int j)
            {
            a=i;
            b=j;
            }
            void meth(Test ox)
            {
            ox.a*=2;
            ox.b/=2;
            }
}
class cbr
{
            public static void main(String[] args)
            {
            Test obj=new Test(4,5);
            System.out.println("Before calling a="+obj.a+" b="+obj.b);
            obj.meth(obj);
            System.out.println("After  calling a="+obj.a+" b="+obj.b);
            }
}

O/P:    Before calling a=4 b=5
            After calling a=8 b=2

No comments:

Post a Comment