In this Java program, you will learn how to swap two numbers without using the third or temporary variables in java. In this program, instead of using a temporary variable, we use simple mathematics calculations to swap the numbers.

Java Program to Swap Two Numbers Without Using Third or Temporary Variable

Java Program to Swap Two Numbers Without Using Third or Temporary Variable

//Java Program to Swap Two Numbers Without Using Temporary Variable
public class JavaPrograms {
public static void main(String[] args) {
float first = 5.0f, second = 8.5f;
System.out.println("--Before swap the numbers--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
first = first - second;
second = first + second;
first = second - first;
System.out.println("--After swap the numbers--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}

Output

--Before swap the numbers--

First number = 5.0

Second number = 8.5

--After swap the numbers--

First number = 8.5

Second number = 5.0

Understand the Program

For the operation, storing (first - second) is important. This is stored in a variable first.

first = first - second;

first = 5.0f - 8.5f

Then, we just add second (24.5f) to this number - calculated first (5.0f - 8.5f) to swap the number.

second = first + second;

second = (5.0f - 8.5f) + 8.5f = 5.0f

Now, the second variable holds 5.0f (which was the initial value of the first variable). So, we subtract calculated first (5.0f - 8.5f) from swapped second (5.0f) to get the other swapped number.

first = second - first;

first = 5.0f - (5.0f - 8.5f) = 8.5f

Then, the swapped numbers are printed on the screen using println().

## Comments