DEV Community

yubaraj singh
yubaraj singh

Posted on

Swapping A and B without 3rd variable

So my teacher gave me a task, a simple task to swap two values in our new Java class. That was an easy task as we had a good background in the Programming language. But he stated that no more than two elements were allowed. That seems a tricky one and everyone in the class was clueless cause this was the mathematical approach for solving.
So it was a bit confusing and after finding a solution I was a bit surprised as there was indeed a better technique for swapping.
steps
* add a and b and assign to a
* subtract a from b and assign to b
* subtract a from b and assign to a
Now, this became our simple swapping without using the third parameter.
Here is a code in java.

class SwapTest {

  public static void main(String arg[]) {
    int a = 999999999;

    int b = 999999999;
    a = a + b;
    b = a - b;
    a = a - b;
    System.out.println("a=" + a + " b=" + b);
  }
}
Enter fullscreen mode Exit fullscreen mode

disadvantage of this method in java is that while using integer it will overflow when the number is large

Top comments (2)

Collapse
 
lucasscharf profile image
Aleatório

You can do the same with XOR operator and without the problem of overflow:

class SwapTest {

  public static void main(String arg[]) {
    int a = 1;
    int b = 2;

    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    System.out.println("a=" + a + " b=" + b);
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yubarajsingh profile image
yubaraj singh

wow, thanks for that trick.