swap three variables in java without using temporary variable

Let’s learn to swap three variables in java without using temporary variable.

swap three variables in java without using temporary variable

In the below example we are using arithmetic operators to swap three variables without using temporary variable.

public class SwapThreeNumbersWithoutTemp
{
   static int num1, num2, num3;
   public static void main(String[] args) 
   {
      num1 = 30; num2 = 60; num3 = 90; 
      System.out.println("Before swapping three numbers: num1 = " + num1 + ", num2 = " + num2 + ", num3 = " + num3);
      swapWithoutTemporary();
      System.out.println("After swapping three numbers: num1 = " + num1 + ", num2 = " + num2 + ", num3 = " + num3);
   }
   static void swapWithoutTemporary() 
   { 
      num1 = num1 + num2 + num3; 
      num2 = num1 - (num2 + num3); 
      num3 = num1 - (num2 + num3); 
      num1 = num1 - (num2 + num3);  
   }
}


Output:

Before swapping three numbers: num1 = 30, num2 = 60, num3 = 90
After swapping three numbers: num1 = 90, num2 = 30, num3 = 60


Also read – nested classes in java