Tutorials

# Java Swap Program

In this chapter of the java programming tutorial, we are going to write a simple java program to:

• swap two numbers using third variable
• swap two numbers without using third variable

### Java Program to Swap Numbers using 3rd variable

``````package BasicPrograms;

public class TihSwapVariable {

public static void main(String[] args) {
int a = 101;
int b = 201;
int c;  //using third variable

System.out.println("Before swap a="+ a+ " b="+ b);

//Swap operation
c = b;
b = a;
a = c;

System.out.println("After swap a="+ a+ " b="+ b);

}

}
``````

OUTPUT

Before swap a=101 b=201
After swap a=201 b=101

Calculation logic
a=101, b=201
c=201
b=101
a=201
Thus we get, a=201, b=101

### Java program to swap two numbers

Given below is a java program to swap two numbers without using third variable.

``````package BasicPrograms;

public class TihSwap {

public static void main(String[] args) {
int a = 101;
int b = 201;
System.out.println("Before swap a="+ a+ " b="+ b);

//swap variables
a = a - b;
b = a + b;
a = b - a;

System.out.println("After swap a="+ a+ " b="+ b);

}

}
``````

OUTPUT

Before swap a=101 b=201
After swap a=201 b=101

Calculation logic

a=101, b=201

a = 101 - 201 = -100    [a=a-b]

In the following statement, the value of a will be -100

b = -100 + 201 = 101   [b=a+b]

In the following statement, the value of b will be 101

a = 101 - (-100) = 201  [a=b-a]

Thus we get, a=201, b=101