You can swap two numbers in Java without using a third variable by using arithmetic operations (addition and subtraction) or bitwise XOR operations. Here are two common approaches:
1.Using Arithmetic Operations (Addition and Subtraction):public class SwapNumbersWithoutThirdVariable {
public static void main(String[] args) {
int a = 5;
int b = 10;
a = a + b; // a now contains the sum of a and b
b = a - b; // b now contains the original value of a
a = a - b; // a now contains the original value of b
System.out.println("After swapping, a = " + a);
System.out.println("After swapping, b = " + b);
}
}
2.Using Bitwise XOR Operation:public class SwapNumbersWithoutThirdVariable {
public static void main(String[] args) {
int a = 5;
int b = 10;
a = a ^ b; // a now contains the XOR of a and b
b = a ^ b; // b now contains the original value of a
a = a ^ b; // a now contains the original value of b
System.out.println("After swapping, a = " + a);
System.out.println("After swapping, b = " + b);
}
}
Both of these methods work by manipulating the values of the two variables to achieve the swap without using a third variable. However, the bitwise XOR approach is usually faster as it does not involve addition or subtraction.