How to swap two number in Java without using third variable ?

0 0
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
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment

Verified by MonsterInsights