README.md
December 5, 2022 ยท View on GitHub
Description
Do you think it is possible to swap values between two variables without using a third temporary variable? What? No? Yes? Well, the answer is...YES. Take a look at the code and don't forget to vote!
More Info
| Submitted On | |
| By | FAzle AreFin |
| Level | Beginner |
| User Rating | 4.7 (28 globes from 6 users) |
| Compatibility | Java (JDK 1.1), Java (JDK 1.2) |
| Category | Calculators & Science |
| World | Java |
| Archive File |
Source Code
/*
Swap Magic
Swaps values between two variables without using a third temporary variable
Programmer: Fazle Arefin
*/
public class SwapMagic {
public static void main(String args[]) {
// declare and initialize two variables
int a = 10;
int b = 20;
System.out.println("Before swapping a = " + a + " and b = " + b);
a = a + b;
b = a - b;
a= a - b;
/*
instead of + and - you can use * and / respectively
a = a * b;
b = a / b;
a= a / b;
instead of + and - or * and / you can use the XOR operator ^
but this restricts you to only swapping integers
a = a ^ b;
b = a ^ b;
a= a ^ b;
*/
System.out.println("Before swapping a = " + a + " and b = " + b);
}
}