Swap two numbers in Java


On this page, we are going to swap the value of two integers. Sometimes you need to swap/interchange the value of the variable or sometimes this question has been asked in the interview.

Swap value without using Third/Temp Variable

In this example, we have swapped the value of two integers without using any other variable.

SwapValueExp1.java
package org.websparrow;

import java.util.Scanner;

public class SwapValueExp1 {
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter the value of firstVariable = ");
		int firstVariable = scanner.nextInt();
		System.out.print("Enter the value of secondVariable = ");
		int secondVariable = scanner.nextInt();

		System.out.println("Value before swap: firtVariable= " + firstVariable + " secondVariable= " + secondVariable);

		firstVariable = firstVariable + secondVariable;
		secondVariable = firstVariable - secondVariable;
		firstVariable = firstVariable - secondVariable;

		System.out.println("Value after swap: firtVariable= " + firstVariable + " secondVariable= " + secondVariable);
	}
}

Output:

Enter the value of firstVariable = 22
Enter the value of secondVariable = 12
Value before swap: firtVariable= 22 secondVariable= 12
Value after swap: firtVariable= 12 secondVariable= 22

Swap value using Third/Temp Variable

In this example, we have swapped the value of two integers using third/temp variable.

SwapValueExp2.java
package org.websparrow;

import java.util.Scanner;

public class SwapValueExp2 {
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter the value of firstVariable = ");
		int firstVariable = scanner.nextInt();
		System.out.print("Enter the value of secondVariable = ");
		int secondVariable = scanner.nextInt();

		System.out.println("Value before swap: firtVariable= " + firstVariable + " secondVariable= " + secondVariable);

		int temp = firstVariable;
		firstVariable = secondVariable;
		secondVariable = temp;
		System.out.println("Value after swap: firtVariable= " + firstVariable + " secondVariable= " + secondVariable);
	}
}

Output:

Enter the value of firstVariable = 22
Enter the value of secondVariable = 12
Value before swap: firtVariable= 22 secondVariable= 12
Value after swap: firtVariable= 12 secondVariable= 22

Similar Posts

About the Author

Websparrow
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.