Rest all things will be the same as the above program. Only the logic will change. Here, we are assigning x with the value x + y which means x will have a sum of both x and y.
Then, we are assigning y with the value x – y which means we are subtracting the value of y from the sum of (x + y). Till here, x still has the sum of both x and y. But y has the value of x.
Finally, in the third step, we are assigning x with the value x – y which means we are subtracting y (which has the value of x) from the total (x + y). This will assign x with the value of y and vice versa.
1 | import java.util.Scanner; |
2 | |
3 | class SwapTwoNumberWithoutThirdVariable |
4 | { |
5 | public static void main(String args[]) |
6 | { |
7 | int x, y; |
8 | System.out.println( "Enter x and y" ); |
9 | Scanner in = new Scanner(System.in); |
10 | |
11 | x = in.nextInt(); |
12 | y = in.nextInt(); |
13 | |
14 | System.out.println( "Before Swapping\nx = " +x+ "\ny = " +y); |
15 | |
16 | x = x + y; |
17 | y = x - y; |
18 | x = x - y; |
19 | |
20 | System.out.println( "After Swapping without third variable\nx = " +x+ "\ny = " +y); |
21 | } |
22 | } |
Output:
Enter x and y
45
98
Before Swapping
x = 45
y = 98
After Swapping without a third variable
x = 98
y = 45
45
98
Before Swapping
x = 45
y = 98
After Swapping without a third variable
x = 98
y = 45