DEV Community

Discussion on: Swapping A and B without 3rd variable

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.