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.
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)).
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With