Saturday 25 May 2013

call by value and call by reference

Tags

CALL BY VALUE:  

Look at first example:


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. Here the operation occur inside disp() have no effect on the values of a and b used in the call. Their values didn't change to 198 and 38.


class Hello 
 { 
   void disp(int i,int j)
    { 
        i*=2; j/=2; 
    }
 } 
class T7 
{
    public static void main(String as[]) 
   {
     int a=99; 
     int b=77; 
     System.out.println("before call");
     System.out.println("a="+a);
     System.out.println("b="+b);
     Hello h=new Hello(); 
     h.disp(a,b); 
     System.out.println("AFTER call");
     System.out.println("a="+a);
     System.out.println("b="+b); 
  } 

 OUTPUT
 before call a=99 b=77 AFTER call a=99 b=77





CALL BY REFERENCE:




class Hello
 {
      int a,b; Hello(int i,int j)
      {
           a=i; b=j;
      }
      void disp(Hello o) //pass an object
      {
           o.a*=2; o.b/=2;
      }
 }
 class T6
{
      public static void main(String as[])
      {
           Hello h=new Hello(15,20);
           System.out.println("before call");
           System.out.println("a="+h.a);
           System.out.println("b="+h.b); h.disp(h);
           System.out.println("AFTER call");
           System.out.println("a="+h.a);
           System.out.println("b="+h.b);
      }
 }
 OUTPUT: before call a=15 b=20 AFTER call a=30 b=10

When you pass an object to a method the situation change dramatically. Because objects are passed by Reference. When you creating a variable of a class type ,  you are only creating a reference to an object. change to the object inside the method do effect the object used as an argument. When object reference is passed to a method, the reference itself is passed by use of call-by-value.


EmoticonEmoticon