C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Swap Two Numbers Using Temp Variable - Java Program

public class SwapUsingTemp {

    public static void main(String[] args) {

       

        int a = 10;

        int b = 20;

 

        System.out.println("Before Swapping:");

        System.out.println("a = " + a);

        System.out.println("b = " + b);

 

        // Swapping using temp variable

        int temp = a;

        a = b;       

        b = temp;    

 

        System.out.println("\nAfter Swapping:");

        System.out.println("a = " + a);

        System.out.println("b = " + b);

    }

}

Output

 
OUTPUT :
Before Swapping:
a = 10
b = 20

After Swapping:
a = 20
b = 10

Explanation (Step-by-Step)

 Step 1 — Initialize Variables

int a = 10;

int b = 20;

Two variables a and b are assigned values.

 Step 2 — Display Before Swap Values

Prints:

a = 10

b = 20

 Step 3 — Use Temp Variable

int temp = a;

temp stores the value of a.

Now:

  • temp = 10
  • a = 10
  • b = 20

 Step 4 — Assign b to a

a = b;

Now:

  • a = 20
  • b = 20
  • temp = 10

 Step 5 — Assign temp to b

b = temp;

Now:

  • a = 20
  • b = 10
  • temp = 10

The values are successfully swapped.