Swap Two Numbers Without Using Third Variable In Java
Chapter:
Miscellaneous
Last Updated:
02-06-2023 05:21:11 UTC
Program:
/* ............... START ............... */
public class NumberSwapper {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println("Before swapping:");
System.out.println("a = " + a);
System.out.println("b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping:");
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
/* ............... END ............... */
Output
Before swapping:
a = 5
b = 10
After swapping:
a = 10
b = 5
Notes:
-
In this code, the values of a and b are swapped without using a third variable. Here's how it works:
- Initially, a is assigned to a + b, which adds the values of a and b together.
- Then, b is assigned to the difference between a and b. At this point, b holds the original value of a.
- Finally, a is assigned to the difference between the updated value of a (previously a + b) and b. Now, a holds the original value of b. After these operations, the values of a and b have been swapped.