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.


call-by-value 


Pass by value in java means passing a copy of the value to be passed.  In Java the arguments are always passed by value.In case of call by value original value is not changed. 

Example of call by value in java

class Operation
{  
 int data=50;  
  
 void change(int data)
{  
 data=data+100;//changes will be in the local variable only  
 }  
     
 public static void main(String args[])
{  
   Operation op=new Operation();  
  
   System.out.println("before change "+op.data);  
   op.change(500);  
   System.out.println("after change "+op.data);  
  
 }  
}  

Output:
before change 50
after change 50

call-by-reference


Pass by reference in java means the passing the address itself.In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed.

Example of call-by-reference in java

class Operation2
{  
 int data=50;  
  
 void change(Operation2 op)
{  
 op.data=op.data+100;//changes will be in the instance variable  
 }  
     
    
 public static void main(String args[])
{  
   Operation2 op=new Operation2();  
  
   System.out.println("before change "+op.data);  
   op.change(op);//passing object  
   System.out.println("after change "+op.data);  
  
 }  
}  

Output:
before change 50
after change 150

No comments:

Post a Comment