Skip to content
Related Articles

Related Articles

Java Program to Swap Two Numbers
  • Last Updated : 10 Dec, 2020

Problem Statement: Given two integers m and n. The goal is simply to swap their values in the memory block and writing the java code demonstrating approaches.

Illustration:

Input  : m=9, n=5
Output : m=5, n=9
 
Input  : m=15, n=5
Output : m=5, n=15
Here 'm' and 'n' are integer value

Approaches:

There are 3 standard approaches to swap numbers varying from space and time complexity.

  1. Creating an auxiliary memory cell in the memory.
  2. Without creating any auxiliary(additional) memory cell
  3. Using exclusive OR (Bitwise XOR) operator



Approaches are described below individually in same order as listed above:

Approach 1: Swapping the Values Using Third Variable

A memory cell will be created in the memory of the same type occupying same memory in stack area of memory. During execution, it holds on one value to replace others values, once desired execution is completed its value is assigned to already existing second variable. Once scope for the variables are three variables are released from memory cell. This variable is called temporary variable or sometimes referred as catalyst as the involvement in output is not even traced out but executions will halt to produce desired result above witnessed.

Java




// Java Program to Swap Two values using third variable
// using temp variable
 
// Importing generic libraries
import java.util.*;
 
class GFG {
 
    // Finction to swap two numbers
    // Using temporary variable
    static void swapValuesUsingThirdVariable(int m, int n)
    {
        // Swapping the values
        int temp = m;
        m = n;
        n = temp;
        System.out.println("Value of m is " + m
                           + " and Value of n is " + n);
    }
 
    // Main driver code
    public static void main(String[] args)
    {
        // Random integerslues
        int m = 9, n = 5;
 
        // Calling above function to
        // reverse the numbers
        swapValuesUsingThirdVariable(m, n);
    }
}
Output
Value of m is 5 and Value of n is 9

Approach 2: Swapping the Values Without Using Third Variable by using sum and differences concepts of maths.

Algorithms: There are 3 standard steps as listed below: 

  1. Difference of second number from the first number is stored in memory cell where first number was already stored.
  2. Sum of both the numbers  is stored in second memory cell(number).
  3. Difference of first number from the second is computed and stored in memory cell where at initial first value was stored.

Below is the implementation of swapping the numbers without creating any auxiliary space in memory:

Java




// Java Program to swap the two values
// without using third variable
 
// Importing generic Java libraries
import java.util.*;
 
class GFG {
 
    // Function to swap valus of two numbers
    // without creaing temp variable
    static void swapValuesWithoutUsingThirdVariable(int m,
                                                    int n)
    {
        // Steps as listed in algorithm
 
        // Difference of 2nd from 1st
        // is stored in first variable
        m = m - n;
 
        // Sum is stored in second variable
        n = m + n;
 
        // Difference of 1st from 2nd
        // is replaced in first variable
        m = n - m;
 
        // Print numbers
        System.out.println("Value of m is " + m
                           + " and Value of n is " + n);
    }
 
    //  Main driver method
    public static void main(String[] args)
    {
        // Random numbers of integer type
        int m = 9, n = 5;
 
        // Above function is called in main
        // to print swapped values of numbers
        swapValuesWithoutUsingThirdVariable(m, n);
    }
}
Output



Value of m is 5 and Value of n is 9

Approach 3: Swapping the Values Using Operator

Bit-wise operators are used to perform manipulation of individual bits of a number. They can be used with any of the integral types (char, short, int, etc). They are used when performing update and query operations of Binary indexed tree.

This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of input values, i.e, if corresponding bits are different, it gives 1, else it gives 0.

Illustration:

a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7
  0101
^ 0111
 ________
  0010  = 2 (In decimal)

This is the most optimal method as here directly computations are carried on over bits instead of bytes as seen in above two methods. Here’s a Java program to show internal working –

Java




// Java Program to swap the two values
// using XOR Operator
 
// Importing generic Java libraries
import java.io.*;
 
class GFG {
 
    // Function to swap values of two numbers
    // using XOR operator
    static void swapValuesUsingXOROperator(int m, int n)
    {
        // Logic of XOR operator
        m = m ^ n;
        n = m ^ n;
        m = m ^ n;
 
        System.out.println("Value of m is " + m
                           + " and Value of n is " + n);
    }
 
    // Main driver method
    public static void main(String[] args)
    {
        // Random two integer numbers
        // to get swapped
        int m = 9, n = 5;
 
        // Calling the function in main method
        // to get above integer numbers swapped
        swapValuesUsingXOROperator(m, n);
    }
}
Output
Value of m is 5 and Value of n is 9

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :