TeachingBee

Swapping Of Two Numbers In Java

Swapping Of Two Numbers In Java

Swapping of two numbers In java is a common operation that involves exchanging the values of two variables. Having a solid grasp on approaches to swapping numbers is fundamental for any programmer.

In this article we will focus on how to swap two numbers using temporary variable and without using temporary variable. Let’s get started.

Problem Statement

The goal of swapping two numbers in java is simple: exchange the values stored in two variables. For example, if we have:

int a = 5;
int b = 10;

We want to swap so that:

a = 10
b = 5

In this article, we will explore several techniques for swapping two numbers in Java. Let’s get started!

Techniques For Swapping Of Two Numbers in Java

There are a few different ways to swap two numbers in java. In this article, we will cover techniques like

  • The classic approach of swapping using a temporary variable
  • Swapping without a temporary variable using math operations like addition and subtraction
  • Swapping using XOR operator

Swap Two Numbers In Java Using Temporary Variable

The classic way to swap two numbers in Java is by using a temporary variable. The primary purpose of this temporary variable is to hold the value of one of the numbers, thereby preventing its loss during the swap process. Here are the steps:

Step 1: Declare three variables – two to hold the original numbers and one temporary variable.

int a = 5;
int b = 10;
int temp;

Step 2: Save the value of one variable in the temporary variable.

temp = a;

Step 3: Assign the value of the other variable to the first variable.

a = b;

Step 4: Assign the value stored in the temporary variable to the second variable.

b = temp;

After this swap, a will contain 10 and b will contain 5. The temporary variable temp was used to hold one value so we could overwrite the other variable.

Java Code Implementation

Here is the full Java code to demonstrate swapping two numbers using a temporary variable:

// Swapping two numbers using a temporary variable

public class SwapNumbers {

  public static void main(String[] args) {
    
    int a = 5;
    int b = 10; 
    
    // Swap numbers using temporary variable
    int temp = a;
    a = b;
    b = temp;
    
    System.out.println("After swapping:");
    System.out.println("a = " + a);
    System.out.println("b = " + b);
  }

}

Output

After swapping:
a = 10
b = 5

In this example, a and b originally contain 5 and 10. We created a temporary variable temp to hold the value of a. Then, we overwrite a with the value of b, and b with the value stored in temp. This successfully swaps the values between the two variables.

The temporary variable provides a placeholder to store one value so we can overwrite the other variable. This is a simple and effective technique for swapping two numbers in Java.

Swap Two Numbers In Java Without Using Temporary Variable

In the previous section, we covered swapping numbers using a temporary variable. However, it is also possible to swap variables without needing an extra temporary variable. Here we will explore some techniques for swapping without a temp variable.

Mathematical Magic: Using Addition and Subtraction

We can actually swap two numbers by using basic math operations! Here is how:

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

Let’s break this down:

Let’s assume a = 5 and b = 10

Step 1: a = a + b

  • a now becomes 5 + 10 = 15

Step 2: b = a – b

  • We take the new value of a, which is 15, and subtract the original value of b, which is 10. So, mathematically seeing b = (a+b-b), by putting value of a from previous step.
  • So, b now becomes 15 – 10 = 5.

Step 3: a = a – b

  • Finally, we take the new value of a, which is 15, and subtract the new value of b, which is 5. So, mathematically seeing a = (a+b- a)), by replacing values of a and b from previous step.
  • So a now becomes 15 – 5 = 10

This cleverly swaps a and b without requiring a temporary variable.

Java Code Implementation

// Swap two numbers in Java using Addition and Subtraction

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;

        System.out.println("Before swap: a = " + a + ", b = " + b);

        // Swapping without a temporary variable using addition and subtraction
        a = a + b; // Step 1: a now holds the sum of a and b
        b = a - b; // Step 2: b now holds the original value of a
        a = a - b; // Step 3: a now holds the original value of b

        System.out.println("After swap: a = " + a + ", b = " + b);
    }
}

Output

Before swap: a = 5, b = 10
After swap: a = 10, b = 5

This method is quite elegant and minimizes the use of extra space for a temporary variable. However, as mentioned earlier, it’s crucial to be aware of the potential for integer overflow if the numbers are large enough that their sum exceeds the maximum value an int can hold in Java.

If there’s a risk of overflow, then this method should be avoided in favor of a safer approach, such as using a temporary variable or the bitwise XOR method.

Swapping Using Bitwise XOR

The bitwise XOR (exclusive OR) operator (^) can also be used to swap two numbers. To understand this technique, we first need to know how the XOR operator works:

  • If the bits at a given position are different, XOR will return 1 for that bit position
  • If the bits are the same, XOR will return 0 for that bit position
XYX^Y
000
011
101
110
Truth table for XOR

For example:

  0101 (5 decimal)
   XOR
  1010 (10 decimal)
= 1111 (15 decimal)

The swapping using XOR takes advantage of the fact that a ^ b ^ b = a. Here’s how it works:

a = a ^ b; // a now contains  a XOR b
b = a ^ b; // b now contains  original a XOR original b XOR original b = original a
a = a ^ b; // a now contains  original a XOR original b XOR original a = original b

Java Code Implementation

// Swap Two numbers In Java  using XOR

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;

        System.out.println("Before swap: a = " + a + ", b = " + b);

        // Swapping without a temporary variable using XOR
        a = a ^ b; // Step 1: a now holds the XOR of a and b
        b = a ^ b; // Step 2: b now holds the original value of a
        a = a ^ b; // Step 3: a now holds the original value of b

        System.out.println("After swap: a = " + a + ", b = " + b);
    }
}

Output

Before swap: a = 5, b = 10
After swap: a = 10, b = 5

The XOR swap is a bit tricky to understand at first, but it’s a neat trick that doesn’t run into the overflow issue that the addition and subtraction method does. It’s also worth noting that the XOR operation is generally very fast.

Key Takeaways

To conclude:

  • Using a temporary variable is the classic approach to swapping two values. It involves saving one value in the temp variable so you can overwrite the other variable.
  • Math operations like addition/subtraction can swap variables without a temporary variable. This relies on reassigning values in a cyclic way.
  • Bitwise XOR can swap values by leveraging the XOR properties where a ^ b ^ b = a. This allows swapping without a temp variable.

Similar Posts

Add Days To The Current Date in Java

Calculate Area of Hexagon in Java

Program to Calculate EMI in Java

Calculate Area of a Circle in Java

Leap Year Program In Java

Checkout more Java Tutorials here.

I hope You liked the post ?. For more such posts, ? subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.

FAQ

What are the advantages and disadvantages of using arithmetic operations to swap numbers?

Are there any special considerations when swapping different data types, such as integers and doubles?

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

ascii value in java

Print ASCII Value in Java

In this article we will into the ASCII table in C, exploring its various character sets—from control characters to printable characters, including letters, digits, and special symbols—and demonstrates how to

data hiding in java

Data Hiding In Java

In this article we will discuss data hiding in Java which is an important concept in object-oriented programming. We will cover So let’s get started. What is Data Hiding in

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In