Make sure to subscribe to our newsletter and be the first to know the news.
Make sure to subscribe to our newsletter and be the first to know the news.
Number swapping is a common programming exercise where the values of two variables are exchanged.
Understanding the Code:
1. The provided Java code demonstrates how to swap the values of two variables (number1 and number2) without using a temporary variable.
2. Initially, two integer variables number1 and number2 are assigned values 10 and 20 respectively.
3. The original values of number1 and number2 are printed to the console.
4. number1 is updated to hold the sum of its original value and number2.
5. number2 is updated to hold the difference between the updated number1 and its original value (which effectively stores the original value of number1).
6. Finally, number1 is updated to hold the difference between its current value (which is the sum of the original number1 and number2) and the new value of number2. After this step, number1 holds the original value of number2, and number2 holds the original value of number1.
7. The values of number1 and number2 after swapping are printed to the console.
public class SwapTwoNumbers {
public static void main(String[] args) {
int number1=10;
int number2=20;
System.out.println("Before Swap");
System.out.println("n1 -"+number1+" || n2 -"+number2);
number1=number1+number2;
number2=number1-number2;
number1=number1-number2;
System.out.println("After Swap");
System.out.println("n1 -"+number1+" || n2 -"+number2);
}
}
Conclusion : Number swapping is a fundamental concept in programming, showcasing the manipulation of variables and their values. The Java program presented here provides a clear illustration of how this operation can be achieved efficiently.