by Dinesh Thakur Category: Classes

In Java, there is no such thing as a call by reference, only a call by value. If a method that passes value called, we are calling by value and any change in the method called do not get affected in the method used to call.  Where a call by value is used, there is no change to the original value. Have a look  at the Example below:

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

This method copies the value of an argument into the formal parameter of the method. Therefore, changes made to the parameter of the method are limited to that method only and there is no impact of changes on the argument. That is, when control returns to the caller method, earlier values of the arguments seen.
And here’s another example:

In call by reference method, a reference to an argument (not the value of the argument) passed to the parameter. Inside the method, this reference is used to access the actual argument specified in the call. It means that changes made to the parameter affect the actual argument also. When the control returns to the caller method, the changes made in the method can be seen in the arguments in the caller method too.
In Java, when we pass a simple type to a method, it is passed by value. When we create a variable of a class, we are only creating a reference to an object. Thus, when we pass this reference method, the parameter that receives it refers to the same object as that referred by the argument. It means that objects are passed to methods by reference.

class Operation2 {
   int data=50;
   void change(Operation2 op){
      op.data = op.data+100;//changes will be made 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);
   }
}
The output of this:
before change 50
after change 150



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles