Swap Program In Java

In this problem, we need to swap numbers in java. Swapping is the process of changing the values kept in two variables. The values of two variables can be changed in a variety of ways. Simple mathematical operations like addition and subtraction, multiplication and division, or bitwise XOR can also be used to perform the swap process. It can also be switched using a temporary variable.
Say we have to change var2’s value to var1 and vice versa. We have two variables, var1 and var2. The switching of values is the process in question. We are trading the values of two variables, to put it simply. In this post, we’ll examine the many Java methods for switching the values of two variables.

Swap Two Numbers in Java Using Temporary Variable

Let us think of a real-life example. Let’s say you have two boxes: one with a red ball and the other with a black ball. The balls in the two boxes should be exchanged. You want to swap the balls in the two boxes.

How will you do this?

You can use a temporary box as assistance. You can keep the red ball in the box that holds the black ball while keeping the black ball in the temporary box. Later, you can remove the black ball from the temporary container and store it inside the box that originally held the red ball.

How can this solution be turned into a function?

The initial variable’s value will be transferred to a temporary variable that will be created later. The temporary box we used in the "box and ball" example is similar to this. Just as we modified the position of the balls in the box, we will later assign the value of the second variable to the first variable before assigning the value of the temporary variable to the second variable.

Java Program to Swap Two Numbers Using Temporary Variable

class Swap {

  public static void main(String[] args) {
    int a = 11, b = 22;

    System.out.println("Before swapping the numbers:");
    System.out.println("First number = " + a);
    System.out.println("Second number = " + b);

    int temp = a; 
    a = b; 
    b = temp; 

    System.out.println("After swapping the numbers: ");
    System.out.println("First number = " + a);
    System.out.println("Second number = " + b);
  }
}

Output

Before swapping the numbers:
First number = 11
Second number = 22
After swapping the numbers:
First number = 22
Second number = 11

The value of the first number and the second number are switched using a temporary variable, as can be seen in the output.

Swap Two Numbers in Java Without Using a Temporary Variable

Previously, we observed the use of a temporary variable to swap two numbers in Java. Let’s now examine a Java method for swapping two numbers without the use of a temporary variable.

Using Arithmetic Addition and Subtraction We learned how to use a temporary variable to swap two numbers. By utilizing only basic math, we can swap two numbers without the use of a temporary variable. Let’s examine the code so that we may subsequently understand its logic.

Java Program to Swap Two Numbers Without Using a Temporary Variable

class Swap {

  public static void main(String[] args) {
    int a = 11, b = 22;

    System.out.println("Before swapping the numbers: ");
    System.out.println("First number = " + a);
    System.out.println("Second number = " + b);

    a = a + b;
    b = a - b;
    a = a - b;

    System.out.println("After swapping the numbers: ");
    System.out.println("First number = " + a);
    System.out.println("Second number = " + b);
  }
}

Output

Before swapping the numbers: 
First number = 11
Second number = 22
After swapping the numbers: 
First number = 22
Second number = 11

Explanation: After viewing the code and the result, let’s examine what transpired in the code to cause the switching of two values. The 10, 11, and 12th lines had their numbers switched.

  • In the line 11, a = a + b, a is assigned the value of a + b, i.e., the sum of given numbers. In this case, a = 10 + 20, i.e., a = 30.
  • In the next step, i.e., b = a – b, we take the difference between the sum (of a and b) and b. Since b is subtracted from the sum of a and b, we got the value of a. Hence, using b = a – b, the original value of a is assigned to b. In this case, we get b = 30 – 20, i.e., b = 10.
  • Till now, we have assigned the value of a in b but we are yet to assign the value of b in a. This is also simple to do.
  • If we subtract the original value of a from the sum, then we will end up with the value of b.
  • So, with a = a – b, the original value of a (currently stored in b) is subtracted from the sum (currently stored in a). Hence, now a contains the original value of b. So, in the last step, i.e., a = a – b, we get a = 30 – 10, i.e., a = 20.

As you can see, we just swapped the two numbers without using a temporary variable.

Note: This method could fail due to arithmetic overflow if the values of a and b are too large since addition might go outside of the integer range.

Swapping Two Number Using Arithmetic Multiplication and Division

class Swap {

  public static void main(String[] args) {
    int a = 11, b = 22;

    System.out.println("Before swapping the numbers: ");
    System.out.println("First number = " + a);
    System.out.println("Second number = " + b);

    a = a * b;
    b = a / b;
    a = a / b;

    System.out.println("After swapping the numbers: ");
    System.out.println("First number = " + a);
    System.out.println("Second number = " + b);
  }
}

Output

Before swapping the numbers: 
First number = 11
Second number = 22
After swapping the numbers: 
First number = 22
Second number = 11

Explanation: This approach also uses multiplication and division to swap two values that are simple to understand from the given code, just like the prior way did.

Note: However, if any one of the integers is 0, this strategy will fail since the product becomes 0 regardless of the other number.

Swapping Two Number Using Bitwise XOR operator

When two numbers a and b are XOR, the result is a number with all bits set to 1 wherever a and b’s bits vary.

Example: In binary, 4 is denoted by 100 and 5, by 101. 5 and 4 can be XORed to produce 001, or 1.

Decimal Binary
Number 5 101
Number 4 100
Bitwise XOR 1 001

Java Program to Swap Two Number Using Bitwise XOR operator

class Swap {

  public static void main(String[] args) {
    int a = 11, b = 22;

    System.out.println("Before swapping the numbers:");
    System.out.println("First number = " + a);
    System.out.println("Second number = " + b);

    a = a ^ b; 
    b = a ^ b; 
    a = a ^ b; 

    System.out.println("After swapping the numbers: ");
    System.out.println("First number = " + a);
    System.out.println("Second number = " + b);
  }
}

Output

Before swapping the numbers:
First number = 11
Second number = 22
After swapping the numbers: 
First number = 22
Second number = 11

Explanation: In this method, we made use of the bitwise XOR operator. Bitwise XOR has two interesting properties:

x ^ x = 0
x ^ 0 = x
^ operator is used to denote xor operation.

So, in line 10, a = a ^ b, the value of a is changed to a ^ b.
In line 11, b = a ^ b. So, b becomes
b = a ^ b = (a ^ b) ^ b = a ^ {b ^ b} = a ^ 0 = a
Thus, the value of a is now stored in b.
And, in line 13, a = a ^ b. So, a becomes
a = a ^ b = (a ^ b) ^ a = (a ^ a) ^ b = 0 ^ b = b
Thus, the value of b is now stored in a as well.
In this way, we successfully swapped the numbers a and b using the bitwise XOR operator.

Note: The above method to swap two numbers works fine with non-zero numbers. But this approach won’t work if any one of the numbers is 0 because the XOR will be equal to the non-zero number and the same will be assigned to both the numbers.

You would now have a thorough understanding of all the many ways to swap two integers in Java after running the above program. I hope you find my site to be useful and helpful.

Other Java Programs

Java Program to Add Two Numbers
Java Program to Check Prime Number
Java Program to Check Whether a Number is a Palindrome or Not
Java Program to Find the Factorial of a Number
Java Program to Reverse a Number
Java Program to search an element in a Linked List
Program to convert ArrayList to LinkedList in Java
Java Program to Reverse a linked list
Java Program to search an element in a Linked List
Anagram Program in Java
Inheritance Program in Java
Even Odd Program in Java
Hello World Program in Java
If else Program in Java
Binary Search Program in Java
Linear Search Program in Java
Menu Driven Program in Java
Package Program in Java
Leap Year Program in Java
Array Programs in Java
Linked List Program in Java
String Programs in Java
Star Program in Java
Number Pattern Program in Java

Leave a Reply

Your email address will not be published. Required fields are marked *