Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap two string variables in Java without using a third variable

Tags:

How do I swap two string variables in Java without using a third variable, i.e. the temp variable?

String a = "one"
String b = "two"
String temp = null;
temp = a;
a = b;
b = temp;

But here there is a third variable. We need to eliminate the use of the third variable.

like image 985
user1281029 Avatar asked Aug 30 '13 08:08

user1281029


People also ask

Can we swap 2 strings in Java?

Swapping two strings usually take a temporary third variable. One of the approach to accomplish this is to concatenate given two strings into first string. Extract string 2 using substring (0, length(string1) - (string2)) i.e. in our case it will be substring(0, (11-4)).

How would you swap 2 strings without a temporary variable in Java?

Method: In order to swap two string variables without using any temporary or third variable, the idea is to use string concatenation and substring() methods to perform this operation.

How do I swap values between two strings?

For swapping two strings from one location to another location, we use strcpy() function. An array of characters (or) collection of characters is called a string.


1 Answers

Do it like this without using a third variable:

String a = "one";
String b = "two";

a = a + b;
b = a.substring(0, (a.length() - b.length()));
a = a.substring(b.length());

System.out.println("a = " + a);
System.out.println("b = " + b);
like image 139
Ankur Lathi Avatar answered Oct 15 '22 13:10

Ankur Lathi