This topic demonstrates about how to swap values between two numbers using java program.

Swapping is the process of exchanging values between any two numbers. Sometimes it is necessory to swap values for futher calculations in the program. We assigns the values to each other using third variable called temp.

**Steps**

- Store first value into temp variable
- Store second value into first variable
- Store temp variable value into second variable

**Example**

import java.util.Scanner; public class SwappingUsingTempEx { public static void main(String[] args) { int first,second,temp; Scanner scan = new Scanner(System.in); System.out.print("Enter two values : "); first = scan.nextInt(); second = scan.nextInt(); System.out.println("Before swapping\n First = "+first+" Second = "+second); temp = first; first = second; second = temp; System.out.println("After swapping\n First = "+first+" Second = "+second); } }

Enter two values : 10

20

Before swapping

First = 10 Second = 20

After swapping

First = 20 Second = 10

20

Before swapping

First = 10 Second = 20

After swapping

First = 20 Second = 10

**Steps**

- Add first and second variable and store result in the first variable
- Subtract first and second variable and store result in the second variable
- Again Subtract first and second variable and store result in the first variable

**Example**

public class SwappingUsingTempEx { public static void main(String[] args) { int first,second; first = 59; second = 23; System.out.println("Before swap\n First = "+first+" Second = "+second); first = first + second; second = first - second; first = first - second; System.out.println("After swap\n First = "+first+" Second = "+second); } }

Before swap

First = 59 Second = 23

After swap

First = 23 Second = 59

First = 59 Second = 23

After swap

First = 23 Second = 59

**Steps**

- Multiply first and second variable and store result in the first variable
- Divide first and second variable and store result in the second variable
- Again Divide first and second variable and store result in the first variable

**Example**

public class SwappingUsingTempEx { public static void main(String[] args) { int first,second; first = 100; second = 60; System.out.println("Before swap\n First = "+first+" Second = "+second); first = first * second; second = first / second; first = first / second; System.out.println("After swap\n First = "+first+" Second = "+second); } }

Before swap

First = 100 Second = 60

After swap

First = 60 Second = 100

First = 100 Second = 60

After swap

First = 60 Second = 100