Swap Two Numbers In Java

Swap Two Numbers In Java: Welcome to all of you. This is another simple Java program for beginners’ series of posts. This tutorial will discuss how to swap two numbers in various ways. But before that, if you are unaware of what it is, let me share with you: “Swapping is nothing but interchange values of the variables”.

For example, let’s take two numbers here: a=5 and B=4. Now, what I mean by swap is after executing the swapping program code, when I print the value of A, it should print the value of A as 4, and then when I print the value of B, it will print 5.

Post Type:Java Programs Tutorial
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

Different Ways to Swap Two Numbers In Java

We can Swap Two Numbers In Java in different ways, and those ways are:

  • Swap two numbers by using the third variable
  • Swap two numbers without using a third variable (+ and -)
  • Swap two numbers without using their variable (Bitwise XOR operator)
  • Swap two numbers without using their variable ( * and /)
  • Single Statement

Swap Two Numbers by Using the Third Variable

package com.softwaretestingo.basic;
public class SwapNumbersEx1 
{
	public static void main(String[] args) 
	{
	    int a=5;
	    int b=4;
	    
	    System.out.println("Before Swap the Value Of A & B: "+a+" "+b);
	    
		int temp;
	    temp=a; // temp=5
	    a=b; //a=4;
	    b=temp; //b=5
	    
	    System.out.println("After Swap the Value Of A & B: "+a+" "+b);

	}
}

Before assigning the value of B to A, we’ll assign that value of A to a variable called temp. Then, once you get the value of A into the Temp variable, you can assign the value of B to A. After that, you can assign the temp variable value to B.

But if you focus on this code, the memory we should be using is only eight bytes. Unfortunately, we are creating one more variable just for the swapping, which means we are wasting extra memory. Instead of going for the third variable, we’ll use some other logic to save this memory.

Swap Two Numbers Without Using the Third Variable ( + and -)

package com.softwaretestingo.basic;
public class SwapNumbersEx2 
{
	public static void main(String[] args) 
	{
	    int a=5;
	    int b=4;
	    
	    System.out.println("Before Swap the Value Of A & B: "+a+" "+b);
	    
	    a = a+b;
	    b = a-b;
	    a = a-b;
	    
	    System.out.println("After Swap the Value Of A & B: "+a+" "+b);
	}
}

Let’s say how it works first so initially, the value of A is five and B is four, which means when you say the new value for A will be nine, right, then the value of B is still four. When the second statement was executed (b = a-b), B is nine minus four, and B becomes five.

In this code, the value of A is nine, and your B value is five, so when you execute this statement (a = a-b;), the value of A becomes four, and you can see we have swapped the number. As you can see here, we are not wasting any extra variables, and that’s the advantage of using logic.

If we can focus on the binary conversion of 5 as 1 0 1 and the binary conversion of four as 1 0 0, it means to represent the numbers five and four, we require only three bits, but during the operation, the value of A becomes nine and the binary format of nine is 1 0 0 1. That means that your result will go from 3 bits to 4 bits during the operation.

Swap Two Numbers Without Using Third Variable – Bitwise XOR (^) operator

To implement this logic, what we’ll do is instead of this plus sign, we’ll use the Bitwise XOR (^) operator. So, this bitwise operator works: If both bits are the same, then the result will be 0, and if there is a mismatch in the bits, then the result will be 1. You can also follow the below table.

ABA XOR B
000
011
101
110

So, when we run the program

package com.softwaretestingo.basic;
public class SwapNumbersEx3 
{
	public static void main(String[] args) 
	{
	    int a=5;
	    int b=4;
	    
	    System.out.println("Before Swap the Value Of A & B: "+a+" "+b);
	    //^ -> XOR 1 1 -> 0, 1 0  -> 1, 0 0  -> 0,  0 1  -> 1 
	    
	    a = a^b; // 1 0 1 XOR 1 0 0  -> 0 0 1
	    b = a^b; // 0 0 1 XOR 1 0 0  -> 1 0 1  ->5
	    a = a^b; // 0 0 1 XOR 1 0 1   ->1 0 0  ->4
	    
	    System.out.println("After Swap the Value Of A & B: "+a+" "+b);
	}
}

Swap Two Numbers Without Using Third Variable ( * and /)

In this way, we will see how to swap the values of two variables without using the third variable, but we are using the help of the multiplication and division operators. But here, we have one condition: the value of a and b should not be Zero.

package com.softwaretestingo.basic;
public class SwapNumbersEx4 
{
	public static void main(String[] args) 
	{
	    int a=5;
	    int b=4;
	    
	    System.out.println("Before Swap the Value Of A & B: "+a+" "+b);
	   
	    a = a*b;
	    b = a/b;
	    a = a/b;
	    
	    System.out.println("After Swap the Value Of A & B: "+a+" "+b);
	}
}

Note: If any variables have zero value, you will get the arithmetic exception.

Swap Two Numbers Using a Single Statement

package com.softwaretestingo.basic;
public class SwapNumbersEx5 
{
	public static void main(String[] args) 
	{
	    int a=5;
	    int b=4;
	    
	    System.out.println("Before Swap the Value Of A & B: "+a+" "+b);
	   
	    b=a+b -(a=b);
	    
	    System.out.println("After Swap the Value Of A & B: "+a+" "+b);
	}
}

Let me explain to you how this will work. As you know, the execution always starts from right to left.

  • Here, (a=b) means the B value will be assigned to A. So, the current value of A is 4.
  • a+b: means the total value becomes 9.
  • b=a+b -(a=b): b=9-4; so finally, the value of b is 5

Already, the value of A has changed to 4. So finally, the values A=4 and B=5.

Conclusion:

Finally, we have reached the end of the simple Java program for beginners series of posts. In this blog post, we have discussed 5 different ways to swap two numbers. I hope this blog post helps you better understand how to do that. Let us know in the comment section if you still have any concerns.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment