Menu

Showing posts with label Swap two Strings. Show all posts
Showing posts with label Swap two Strings. Show all posts

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