Learn to **swap two numbers** in given two Java programs. First program uses a temporary variable while second program does not uses any temp variable.

## 1. Swap two numbers using temporary variable

Given below is a Java program which uses temporary variable `'temp'`

to swap two numbers.

The steps for swapping are simple enough for two given numbers `'x'`

and `'y'`

.

- Assign value of
`'x'`

to`'temp'`

. - Assign value of
`'y'`

to`'x'`

. - Assign value of
`'temp'`

to`'y'`

.

After above steps, value of `'x'`

will be assigned to `'y'`

and value of `'y'`

will be assigned to `'x'`

.

public class Main { public static void main(String[] args) { int temp; int x = 100; int y = 200; //Swapping in steps temp = x; x = y; y = temp; //Verify swapped values System.out.println("x = " + x + " and y = " + y); } }

Program output.

x = 200 and y = 100

## 2. Swap two numbers without temporary variable

This java program is little complex in comparison to previous approach, but it can be asked as java interview question for beginners.

In this approach, we use simple mathematics. We use any one variable from given two variables to **store the sum of both variables**.

Once we have sum in one variable and second variable has original value, we can use these both to get values swapped.

public class Main { public static void main(String[] args) { int x = 100; int y = 200; //Swapping in steps x = x + y; //x = 100 + 200 = 300 y = x - y; //y = 300 - 200 = 100 x = x - y; //x = 300 - 100 = 200 //Verify swapped values System.out.println("x = " + x + " and y = " + y); } }

Program output.

x = 200 and y = 100

Drop me the questions related to above **java programs to swap two given numbers with or without using temporary variable**.

Happy Learning !!

## Leave a Reply