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.
Now Let’s write the program,
Java Program to Swap Two Numbers Using Third Variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class Swapping { public static void main(String[] args){ int a,b,temp; //Declaring all the variables a=10; //assigning value to variable a b=20; //assigning value to variable b //printing the value of a before swapping System.out.println("The value of a before swapping = "+a); //printing the value of b before swapping System.out.println("The value of b before swapping = "+b); //Swapping Logic using temporary variable temp=a; //assigning value of a to temp a=b; //assigning value of b to a b=temp; //assigning value of temp to b //printing the value of a after swapping System.out.println("The value of a after swapping = "+a); //printing the value of b after swapping System.out.println("The value of b after swapping = "+b); } } |
1 2 3 4 |
The value of a before swapping = 10 The value of b before swapping = 20 The value of a after swapping = 20 The value of b after swapping = 10 |
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.