Java Program to Swap Two Numbers Using Third Variable

Hello Everyone, in this tutorial we will learn about Java Program to Swap Two Numbers 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.

For swapping the numbers, we will use the third variable or, say, temporary variable. The logic behind swapping two numbers using the third or temporary variable is below.

  • First of all, we will declare the variables, including the temporary variable.
  • Now, we will assign the values to the variables.
  • Next, we will assign the value of the first variable to the temporary variable.
  • Next, we will assign the value of the second variable to the first variable.
  • Next, we will assign the value of the temporary variable to the second variable.

Java Program to Swap Two Numbers using Third Variable
Now Let’s write the program,

Java Program to Swap Two Numbers 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 temporary variable, which is as follows
    • First of all, assigned the value of variable a to temp variable.
    • Then, assigned the value of variable b to variable a.
    • Then, assigned the value of variable temp to variable b.
  • Then finally, printed the value of the variable after swapping.

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

Leave a Comment