Call By Value

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Call by Value and Call by Reference in Java

There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.

Example of call by value in java

In case of call by value original value is not changed. Let's take a simple example:

  1. class Operation{  
  2.  int data=50;  
  3.   
  4.  void change(int data){  
  5.  data=data+100;//changes will be in the local variable only  
  6.  }  
  7.      
  8.  public static void main(String args[]){  
  9.    Operation op=new Operation();  
  10.   
  11.    System.out.println("before change "+op.data);  
  12.    op.change(500);  
  13.    System.out.println("after change "+op.data);  
  14.   
  15.  }  
  16. }  
Output:before change 50
       after change 50		

Another Example of call by value in java

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. In this example we are passing object as a value. Let's take a simple example:

  1. class Operation2{  
  2.  int data=50;  
  3.   
  4.  void change(Operation2 op){  
  5.  op.data=op.data+100;//changes will be in the instance variable  
  6.  }  
  7.      
  8.     
  9.  public static void main(String args[]){  
  10.    Operation2 op=new Operation2();  
  11.   
  12.    System.out.println("before change "+op.data);  
  13.    op.change(op);//passing object  
  14.    System.out.println("after change "+op.data);  
  15.   
  16.  }  
  17. }  
Output:before change 50
       after change 150