Java Program to Swap Two Numbers

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 {`   `    ``// 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);` `    ``}` `}`

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 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);` `    ``}` `}`

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`

Time complexity: O(1) as it is doing constant operations

Auxiliary Space: O(1)

Approach 4: Using arithmetic operators

This is simplest way to swap the numbers without using any 3rd variable also swap the numbers in single line. In this approach will follow the simple expression to swap the numbers i.e.,  a = (a + b) – (b = a);  Suppose we have value a=10, b=22, if we put these values in mentioned expression then it swap the values. It follows BODMAS rule then first bracket (a+b) i.e., (10+22)=32 then it will solve another bracket (b=a) which simply put the value of a in b i.e., b=10. Now it will subtract 32-10 i.e., a=22. In this way we can swap the numbers easily.

Java

 `public` `class` `HelloWorld{`   `     ``public` `static` `void` `main(String []args){` `         ``int` `a=``10``,b=``22``;` `        ``System.out.println(``"Before swapping Value of a is "` `+ a` `                           ``+ ``" and Value of b is "` `+ b);` `        ``a = (a + b) - (b = a);` `        ``System.out.println(``"After Swapping Value of a is "` `+ a` `                           ``+ ``" and Value of b is "` `+ b);` `        `  `     ``}` `}`

Output

```Before swapping Value of a is 10 and Value of b is 22
After Swapping Value of a is 22 and Value of b is 10```

Time complexity: O(1)

Auxiliary Space: O(1)

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next