Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (1.5k points)

Is it possible to swap two numbers without a third variable and without an arithmetic operator? If yes, how to do that?

1 Answer

0 votes
by (1.4k points)

To swap two number without third variable and without arithmetic operator, we can use following piece of code: 

Example: 

private static void swap() { 

    int a = 5; 

    int b = 6; 

    System.out.println("Before Swaping: a = " + a + " and b= " + b); 

    // swapping value of two numbers without using temp variable and XOR bitwise operator 

    a = a ^ b; // now a is 3 and b is 6 

    b = a ^ b; // now a is 3 but b is 5 (original value of a) 

    a = a ^ b; // now a is 6 and b is 5numbers are swapped 

    System.out.println("After  Swaping: a = " + a + " and b= " + b); 

} 

Feel free to check out  this blog for more Java concepts

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...