swap two numbers in java using call by reference

Let’s learn swap two numbers in java using call by reference.

swap two numbers in java using call by reference

In java, objects are passed by call by reference. Let’s see an example on swap two numbers using call by reference.

class Demo
{
   int num1, num2;
   Demo(int a, int b)
   {
      num1 = a;
      num2 = b;
   }
   void swapNumber(Demo obj)
   {
      int n;
      n = obj.num1;
      obj.num1 = obj.num2;
      obj.num2 = n;
      System.out.println("Inside swap numbers method: ");
      System.out.println("Number 1 = " + obj.num1 + " Number 2 = " + obj.num2);
   }
}
public class SwappingCallByReference 
{
   public static void main(String[] args) 
   {
      Demo obj = new Demo(60, 90);
      System.out.println("Before swapping two numbers: ");
      System.out.println("Number 1 = " + obj.num1 + " Number 2 = " + obj.num2);
      obj.swapNumber(obj);
      System.out.println("After swapping two numbers: ");
      System.out.println("Number 1 = " + obj.num1 + " Number 2 = " + obj.num2);
   }
}


Output:

Before swapping two numbers: Number 1 = 60 Number 2 = 90
Inside swap numbers method: Number 1 = 90 Number 2 = 60
After swapping two numbers: Number 1 = 90 Number 2 = 60


Also read – garbage collection in java