Menu

How to swap two Integer variables without using the third variable?

Swap two integer variable a and b without using any temporary variable.
Set the initial value for two variable and then swap the value from a to b and b to a. Below is the code snippet written in Java programming to swap two variable without using third variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package jorvee;

public class SwapTwoIntegerVariableWithoutUsingTheThirdVariable {

 public static void main(String[] args) {
  int a=5, b=3;
  System.out.println("Before swap value of a: "+a +" and value of b: "+b);
  a = a+b;
  b = a-b;
  a = a-b;
  System.out.println("After swap value of a: "+a +" and value of b: "+b);
 }
}

Output:

Before swap value of a: 5 and value of b: 3
After swap value of a: 3 and value of b: 5

Another approach to do the same. Swap two variable without using third variable 

No comments:

Post a Comment