Site icon

Swap two numbers without using third or temporary variable in java

Swap two numbers without using temporary variable:

 Swap two numbers – XOR method

Suppose, we would like swap two variables x = 4 & y = 7 using XOR method.
Truth table of “Exclusive-OR” or XOR gate is :

X Y  Output
0 0  0
0 1 1
0  1
1 0

Swap two numbers – addition & subtraction method in java

  1. Swap two variables (x = 4 & y = 7) using addition & subtraction.
  2. Initially x = 4 & y = 7
  3. x = x + y = 11
    • x  = 4 + 7 = 11.
  4. x = 11, y  = 7
  5. y = x – y = 4
    • y = 11 – 7 = 4
  6. x = 11, y = 4
  7. x = x – y = 7
    • x = 11 – 4 = 7.
  8. After swap x = 7 & y = 4

 Swap two numbers using multiplication & division in java

  1. Swap two variables (x = 4 & y = 7) using multiplication & division
  2. Initially x = 4 & y = 7
  3. x = x *  y = 28
    • x  = 4 * 7 = 28.
  4. x = 28, y  = 7
  5. y = x / y = 4
    • y = 28 / 7 = 4
  6. x = 28, y = 4
  7. x = x / y = 7
    • x = 28 / 4 = 7.
  8. After swap x = 7 & y = 4

Code: Swap two numbers without temporary variable (java)

package org.learn;

import java.util.Scanner;

public class DemoSwap {

	public static void main(String[] args) {

		try (Scanner scanner = new Scanner(System.in)) {
			System.out.printf("1. Enter first number x : ");
			int x = scanner.nextInt();
			System.out.printf("2. Enter second number y : ");
			int y = scanner.nextInt();

			swapUsingXOR(x, y);
			swapUsingAdditionAndSubstraction(x, y);
			swapUsingMultiplicationAndDivision(x, y);
		}
	}
	
	private static void swapUsingXOR(int x, int y) {
		// swapping number using XOR
		// x = 4 & y = 7
		// x ^ y = 0100 ^ 0111 = 0011 = 3
		// x becomes 3
		x = x ^ y;

		// x ^ y = 0011 ^ 0111 = 0100 = 4
		// y become 4
		y = x ^ y;

		// x ^ y = 0011 ^ 0100 = 0111 = 7
		// x becomes 7
		x = x ^ y;

		System.out.printf("3. Swap numbers by XOR : x = %d, y = %d ",x,y);
	}
	
	private static void swapUsingAdditionAndSubstraction(int x, int y) {
		// x = 4 & y = 7
		// x = 4 + 7 = 11
		// x becomes 11
		x = x + y;

		// x = 11 & y = 7
		// y = 11 - 7 = 4
		// y becomes 4
		y = x - y;

		// x = 11 & y = 4
		// x = 11 - 4 = 7
		// x becomes 7
		x = x - y;

		System.out.printf("\n4. Swap using Addition & subtraction: x = %d, y = %d ",x,y);
	}

	private static void swapUsingMultiplicationAndDivision(int x, int y) {
		// x = 4 & y = 7
		// x = 4 * 7 = 28
		// x becomes 11
		x = x * y;

		// x = 28 & y = 7
		// y = 28 / 7 = 4
		// y becomes 4
		y = x / y;

		// x = 28 & y = 4
		// x = 28 / 4 = 7
		// x becomes 7
		x = x / y;

		System.out.printf("\n5. Swap using multiplication & division: x = %d, y = %d ",x,y);
	}	
}

Output: swap two variables without third variable in java

1. Enter first number x : 4
2. Enter second number y : 7
3. Swap numbers by XOR : x = 7, y = 4 
4. Swap using Addition & subtraction: x = 7, y = 4 
5. Swap using multiplication & division: x = 7, y = 4 
Exit mobile version