Java Program to Swap Two Numbers

17 Jan, 2022
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.
Creating an auxiliary memory cell in the memory.Without creating any auxiliary(additional) memory cellUsing exclusive OR (Bitwise XOR) operator
Creating an auxiliary memory cell in the memory.
Without creating any auxiliary(additional) memory cell
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 librariesimport java.util.*; class GFG {     // Function 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 integer values        int m = 9, n = 5;         // Calling above function to        // reverse the numbers        swapValuesUsingThirdVariable(m, n);    }}
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: 
Difference of second number from the first number is stored in memory cell where first number was already stored.Sum of both the numbers  is stored in second memory cell(number).Difference of first number from the second is computed and stored in memory cell where at initial first value was stored.
Difference of second number from the first number is stored in memory cell where first number was already stored.
Sum of both the numbers  is stored in second memory cell(number).
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 librariesimport java.util.*; class GFG {     // Function to swap values of two numbers    // without creating 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);    }}
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 librariesimport 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);    }}
Value of m is 5 and Value of n is 9
bunnyram19
simmytarika5
adnanirshad158
prachisoda1234
sweetyty
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array