Swap two numbers in java is simple program in java for swapping numbers.

In this tutorial we will see what is swapping,Swapping numbers, Swap program in java.

**What is swapping**: Swapping of two numbers means replacing the numbers.

**How to swap swap two numbers in java ?**

To swap two numbers we use temporary variable. Using temporary variable we swap numbers as follow

Example :

a= 10 , b= 20

temp = a => copy first number to temporarily variable => temp =10

a = b => copy second number to first => a= 20

b = temp => copy temp number to second => b= 10

**Algorithm :**

- Start
- Declare variables
- Take two numbers input from user
- Print numbers before swapping
- Copy first number to third variable
- Next copy second number to first number
- Copy third variable number to first number
- Print Numbers after swapping
- End

## Java program to swap two numbers

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.*; public class Main { public static void main(String[] args) { int x,y,temp; Scanner sc = new Scanner(System.in); System.out.print("Enter two Number : "); x = sc.nextInt(); y = sc.nextInt(); System.out.println("Before swaping:" + " x = " + x + ", y = " + y); temp = x ; x = y; y =temp; System.out.println("After swaping:" + " x = " + x + ", y = " + y); } } |

**Output :**

**Explanation :**

**1. First we declare variable.**

x and y => to store two numbers

temp => temporary variable

**2. Take two number input from user**

x = sc.nextInt(); => x= 10

y = sc.nextInt(); => y =20

**3. Main logic to swapping numbers**

temp = x ; => temp =10

x = y; => x= 20

y =temp; => y=10

**4. Print numbers after swapping numbers**

System.out.println(“After swaping:” + ” x = ” + x + “, y = ” + y);

## Leave a Reply