How to swap two numbers without using a third variable in Java?

Swapping two numbers can be also known as exchanging the numbers between two variables. The swapping of two numbers without using a third variable or a temporary variable can be done by following the below simple steps:

For example, let’s take two numbers x=20 (first variable) and y=30 (second variable),

  1. Add both number (x+y) and store it in first variable (x). ie x = x + y
  2. Now Substract the second number from the first, and store it in y variable. ie. y = x – y
  3. Now to the step two again but store the value in x variable. ie. x = x – y

Let’s see the calculation steps:

x = x + y => x = 20 + 30 => 50
y = x – y => y = 50 – 20 => 30
x = x – y => x = 50 – 30 => 20

Let’s see the logic to do the same,

Solution

SwapTwoNumbers.java

package com.javacodepoint.programs;

public class SwapTwoNumbers {

	public static void main(String[] args) {
		
		//Initiating two integer numbers
		
		int x = 20, y=30;
		
		//Print both number before swapping
		System.out.println("x = "+x+", y= "+y);
		
		//Logic to swap these numbers without using a third variable
		
		x = x + y;		
		y = x - y;		
		x = x - y;
		
		//Printing the both number again after swapping
		System.out.println("x = "+x+", y= "+y);

	}

}

OUTPUT:

x = 20, y= 30
x = 30, y= 20

Java logical programs list


Java Basic Programs

Java String Programs

Java String Array Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Java Programs based on Stream API (Java 8)

Based on Integer Collections