Menu

Showing posts with label Swap two variables without using the third variable. Show all posts
Showing posts with label Swap two variables without using the third variable. Show all posts

How to swap two variable without using temporary variable in java?

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

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 

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

We are going to see how to swap two variable of type String without using any third or temporary variable. 
This is very frequent question asked by interviewer in any Java technical interview.

Below is a simple java program to swap two String variables a and b.

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

public class SwapTwoStringVariableWithoutUsingTheThirdVariable {

 public static void main(String[] args) {
  String a="swap", b="two numbers";
  a= a+b;
  b= a.substring(0, a.length() - b.length());
  a= a.substring(b.length());
  System.out.println("After swaping value of a is: "+a);
  System.out.println("After swaping value of b is: "+b);

 }

}

Output:

After swaping value of a is: two numbers
After swaping value of b is: swap