Java Program to Swap Two Numbers Without using Third Variable

Hello Everyone, in this tutorial we will learn about Java Program to Swap Two Numbers Without using Third Variable. Swapping in Java Programming Language means exchanging values of two variables. For example, suppose there are two variables, a and b; the value of a is 10 and b is 20; after swapping, the value of a will become 20, and the value of b will become 10.

In the previous tutorial, we learned how to swap two numbers using the third variable, but in this tutorial, we will swap the numbers without using the third variable. Instead of that, we will use the addition and subtraction method. The logic is given below.

  • First of all, we will declare the variables.
  • Now, we will assign the values to the variables.
  • Next, we will assign the sum of the first and second variables to the first variable.
  • Next, we will subtract the second variable from the first variable and store this value in the second variable.
  • Next, we will subtract the second variable from the first variable and store this value in the first variable.

Java Program to Swap Two Numbers Without using Third Variable

Algorithm

Now Let’s write the program.

Java Program to Swap Two Numbers Without using Third Variable

Output:

What we Did?

  • First of all, we have created a class and named it Swapping.
  • After that, started main() method of the program.
  • Then, inside the main() method, declared variables.
  • Then, assigned values to the variables.
  • Then, printed the value of the variables before swapping.Then implemented the swapping logic using the addition and subtraction method without using the third variable, which is as follows
    • First of all, assigned the sum of the first and second variables to the first variable.
    • Then, subtract the second variable from the first variable and stored this value in the second variable.
    • Then, subtract the second variable from the first variable and stored this value in the first variable.
  • Then finally, printed the value of the variables after swapping.

The Java program to Swap Two Numbers without Using Third Variable has been successfully completed. In the next tutorial, we will learn Java Program to add two complex numbers.

Leave a Comment