«Back to Home

Core Java

Topics

Call By Value And Call By Reference In Java

Call by value

Pass by value or call by value is a mechanism, where the method passes the value, provided by the caller. Hence, changes made to the formal parameters of the method have no effect on the original values, which were passed by the caller.
 
Call by Reference

Pass by reference or call by reference means that the method gets the location of the variable, which the caller provides. Hence, the changes made to the formal parameters will affect the actual arguments , used to call the method.
 
In Java, there is only call by value, not call by reference. If we call a method passing a value, it is called as call by value. Thus, changes being done in the called method i.e., not affected in the calling method.
 
Let’s see an example of call by value, given below.
 
Code
  1. public class Calculation {  
  2.     int num = 150;  
  3.     void calculate(int num) {  
  4.         num = num + 100//changes will be in the local variable only    
  5.     }  
  6.     public static void main(String args[]) {  
  7.         Calculation c1 = new Calculation();  
  8.         System.out.println("Before Calculate: " + c1.num);  
  9.         c1.calculate(500);  
  10.         System.out.println("After Calculate: " + c1.num);  
  11.     }  
  12. }  
25

Output

26

In the example, shown above, call by value original value is not changed.
 
Let’s see another example, given below.
 
Code
  1. public class Calculation {  
  2.     int num = 150;  
  3.     void calculate(Calculation c1) {  
  4.         c1.num = c1.num + 100//changes will be in the instance variable    
  5.     }  
  6.     public static void main(String args[]) {  
  7.         Calculation c1 = new Calculation();  
  8.         System.out.println("Before Calculate " + c1.num);  
  9.         c1.calculate(c1); //passing object    
  10.         System.out.println("After Calculate " + c1.num);  
  11.     }  
  12. }  
27

Output

28

In the example, shown above, call by reference original value is changed, if we made changes in the called method. If we pass an object in place of any primitive value, the original value will be changed.
 
Summary

Thus, we learnt that In Java, there is only call by value and no call by reference. If we call a method to pass a value, it is called as call by value. Thus, the changes are being done in the called method i.e., not affected in the calling method.