Java Interview Questions ยท Coding Problems
Learn a classic programming trick to swap the values of two integer variables without using a temporary variable. This lesson explores the arithmetic approach.
public class SwapNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Before swap: a = " + a + ", b = " + b);
// Swapping logic starts here
a = a + b; // a now becomes 30
b = a - b; // b becomes 30 - 20 = 10
a = a - b; // a becomes 30 - 10 = 20
System.out.println("After swap: a = " + a + ", b = " + b);
}
}a is declared and initialized with the value 10.b is declared and initialized with the value 20.a and b are printed to the console before the swap.b to a. The variable a now holds the sum of the original two numbers. a becomes 10 + 20 = 30.b from the new value of a. b becomes 30 - 20 = 10. Now, b holds the original value of a.b from the current value of a. a becomes 30 - 10 = 20. Now, a holds the original value of b. The swap is complete.a and b are printed to the console.