Read Time:40 Second
We can swap Two Number in Java without using third variable by the 3 step process.
Step first- y = y + x; // now b become sum of both the numbers Step second- x = y - x; // y - x = (y + x) - x = y (x is swapped) Step third- y = y - x; // (y + x) - y = x (y is swapped)
Let’s start apply above code in your compiler-
public class SwapTwoNumbers { public static void main(String[] args) { int x = 10; int y = 20; System.out.println("x is " + x + " and y is " + y); x = x + y; y = x - y; x = x - y; System.out.println("After swapping, x is " + x + " and y is " + y); } }
After compilation the swapped value is :
Output: x is 10 and y is 20 after swapping, x is 20 and y is 10
Average Rating