Back
Is it possible to swap two numbers without a third variable and without an arithmetic operator? If yes, how to do that?
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 5, numbers are swapped System.out.println("After Swaping: a = " + a + " and b= " + b); }
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 5, numbers 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