Java Program to swap values of two numbers without temporary variable

  • 0
A typical value swapping progran involves use of a temporay storage to store the value of either of the two variables whose values is to be swapped. In here, I would try to make you understand the true logic of the oprogrm. This program is simply based on the fact that java assignment statement, for example,
a = 1 +3;
would add first 1 and 3, after the addition, the value is stored in the left hand value of the storage variable. Now, the program swapping vales is.
package MathUtility;

class SwapNumber
{
 public static void main(String args[])
 {
  int num1, num2;
  
  num1 = Integer.parseInt(args[0]);
  num2 = Integer.parseInt(args[1]);
  
  System.out.println("Values of num1 & num2 are " + num1 + " and " + num2 +" respectively.");
  num1 = num1+num2;
  num2 = num1-num2;
  num1 = num1-num2;
  
  System.out.println("Values of num1 & num2 are " + num1 + " and " + num2 +" respectively.");
 }
}
To compile the program
javac -d . SwapNumber.java
And to run the program
java MathUtility.SwapNumber 2 10
And the sample output to the provided input is
Values of num1 & num2 are 2 and 10 respectively.
Values of num1 & num2 are 10 and 2 respectively.

No comments:

Post a Comment