20

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1281029
  • 1,513
  • 8
  • 22
  • 32

19 Answers19

36

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ankur Lathi
  • 7,636
  • 5
  • 37
  • 49
  • You can simplify the third statement to `a = a.substring(b.length());` – Gaurang Tandon Dec 14 '15 at 13:22
  • @GaurangTandon Yes, you are right. Updated the answer. – Ankur Lathi Dec 16 '15 at 18:52
  • 2
    a+b will create a third string object (strings are immutable) - you are better off using a temp reference - at least you are not creating object. – tapasvi Dec 23 '17 at 20:57
  • You can even shorten it to a single line, `a = b + (b = a).substring(0, 0);`. This still creates temporary string instances for the sake of saving a local variable, so it’s still a fun thing rather than a recommended coding style, but at least, these string instances are cheaper than the concatenation `a + b`… – Holger Apr 03 '18 at 14:46
  • @tapasvi actually, it creates *three* unnecessary string instances, as the `substring` operations produce new strings equivalent but not identical to the original string instances. – Holger Apr 03 '18 at 14:49
12

// taken from this answer: https://stackoverflow.com/a/16826296/427413

String returnFirst(String x, String y) {
    return x;
}

String a = "one"
String b = "two"
a = returnFirst(b, b = a); // If this is confusing try reading as a=b; b=a;

This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined), so the execution order is:

  1. The original value of b is evaluated in order to be passed as the first argument to the function
  2. The expression b = a is evaluated, and the result (the new value of b) is passed as the second argument to the function
  3. The function executes, returning the original value of b and ignoring its new value
  4. You assing the result to a
  5. Now the values have been swapped and you didn't need to declare temp. The parameter x works as temp, but it looks cleaner because you define the function once and you can use it everywhere.
Community
  • 1
  • 1
marcus
  • 5,041
  • 3
  • 30
  • 36
  • 1
    The requirement is swap without using a third variable. By creating a function returnFirst(String x, String y) you are creating 2 new variables as it is pass by value, not reference. – shanraisshan Oct 01 '15 at 07:12
  • The main advantage is that you don't pollute your local scope with an extra variable. Once the function is created, you can use it multiple times without the burden of "temp" variables. It helps the programmer who writes and reads the program, even tho at runtime there will be extra variables anyway. – marcus Oct 01 '15 at 13:01
6
String a="one";
String b="two";

a = a.concat("#" + b);
b = a.split("#")[0];
a = a.split("#")[1];

This will work as long as your string doesn't contain the # character in them. Feel free to use any other character instead.

You could use a possible Unicode character, like "\u001E" instead of the #.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Husman
  • 6,819
  • 9
  • 29
  • 47
  • not bad, my thought as-well. along your sure to use a delimiter thats not inside the strings. – Roger Aug 30 '13 at 09:04
  • 1
    if any string contain '#' value then? – bNd Aug 30 '13 at 09:07
  • As I clearly state, "This will work as long as your String doesnt contain the # character". So to answer your question @BMT, this code wont work in that case. – Husman Aug 30 '13 at 09:12
  • @Husman So your answer doesn't work? Then why bother answering? – xehpuk Sep 26 '15 at 20:24
  • @xehpuk Clearly English is not your main language. It works AS LONG AS your string does not contain the # character. If you are working with plain words, then this is a viable answer. You can replace the # with any other ascii character. Please read the answer and comments before mouthing off useless facts. – Husman Oct 06 '15 at 13:42
  • @Husman I'm understanding your answer. You're saying that your method doesn't work if the string contains the split character. So what do you do if the string may contain any character (which you don't know at compile time) or even does contain every possible character? The question didn't restrict the problem to "plain words". – xehpuk Oct 07 '15 at 10:55
  • @xehpuk you say "which you don't know at compile time" - That is an assumption. The question does not show any user input or say that we don't know the values at compile time. As far as I can see there are 2 string with English words in them. You are jumping to conclusions without the OP telling us what exactly he wants. My answer works for the example code he has shown. If it does not work for their specific circumstances - then it means they have not clarified their question enough, they can comment with further details and ask for a workaround. Thank you. – Husman Oct 09 '15 at 10:00
  • @Husman There's an even simpler solution for his example: `a = "two"; b = "one";` All I'm saying is that we can't assume the content of the strings as long as it isn't specified. I wouldn't take one example as a specification. – xehpuk Oct 09 '15 at 11:25
  • @xehpuk Great, please post your solution and let the OP decide if they want to use it. ALL I'm saying is we need to decide what is reasonable, and what isn't, for all you know this solution is perfect for someones homework but not so good for a missile control system. I quite clearly listed the limitation of my code and there are plenty of experts on this site who can refute if its good or bad. Thank you, once again. – Husman Oct 12 '15 at 13:19
2
public class SwapStringVariable {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String a = "test";
        String b = "paper";

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

        System.out.println(a + " " + b);


    }

}
Engineer
  • 1,436
  • 3
  • 18
  • 33
1

The simplest way is given below:

String a = "one";
String b = "two";
System.out.println("Before swap: " a + " " + b);
int len = a.length();
a = a + b;
b = a.substring(0, len);
a = a.substring(len);
System.out.println("After swap: " a + " " + b);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1
String str1 = "first";
String str2 = "second";

str1 = str2+str1;
str2 = str1.substring(str2.length(),str1.length());
str1 = str1.substring(0,(str1.length() - str2.length()));

System.out.println(str1);
System.out.println(str2);
1
String name = "george";
String name2 = "mark";
System.out.println(name+" "+name2);
System.out.println(name.substring(name.length()) + name2 +  " "+ name );

Here substring(); method returns empty string. hence , names can be appended.

0

Here you go. Try this:

String a = "one";
String b = "two";
//String temp=null;
int i = a.length();
a += b;
b = a.substring(0, i);
a = a.substring(i, a.length());
System.out.println(a + " " + b);

Take any value in as string in a variable. It will be swap.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
commit
  • 4,777
  • 15
  • 43
  • 70
  • The a+b concatenation is way more expensive than explicitly declaring a third String reference, it just hides what it does: makes a new StringBuilder and makes a new String from that. – blgt Aug 30 '13 at 09:01
  • @blgt it do not matter even in thousands of characters, it will be performed in fractions of milliseconds, suggest if you have really better idea in this code. – commit Aug 30 '13 at 09:05
  • int i = a.length(), looks like a declaration of a 3rd variable to me, defeats the purpose of this exercise. – Husman Aug 30 '13 at 09:10
  • @commit Certainly, if you run it once, and not in a resource-constrained environment. I was just suggesting the the code in the original question will use both less space and time than the suggested answer. And no, I don't have a better solution. To be honest I don't really think the question makes a whole lot of sense. – blgt Aug 30 '13 at 09:10
  • @Husman than we can simply replace `i` with `a.length()` depends on the programmer how he want to access, according to me calling length method of the variable is costlier than storing it when you are accessing more than once because it is going to read that string starting counter and read up to end of the string. Still I will say same it's depend upon the programmer. Right? – commit Aug 30 '13 at 09:30
  • No, a.length() will vary as you change the variables around. What you suggest wont work without storing it inside a variable. – Husman Aug 30 '13 at 09:35
  • Yes, you are right in that case @Ankur Lathi's suggestion will work. – commit Aug 30 '13 at 09:47
0
Community
  • 1
  • 1
armysheng
  • 133
  • 7
0

Jj Tuibeo's solution works if you add replaceFirst() and use a regular expression:

a += b;
b = a.replaceFirst(b + "$", "");
a = a.replaceFirst("^" + b, "");
Community
  • 1
  • 1
troy
  • 165
  • 1
  • 4
0

For String Method 1:

public class SwapWithoutThirdVar{  
public static void main (String args[]){    
 String s1 ="one";
 String s2 ="two";
 s1= s1+s2;
 s2 = s1.substring(0,(s1.length()-s2.length()));
 s1 = s1.substring(s2.length()); 
 System.out.println("s1 == "+ s1);
 System.out.println("s2 == "+ s2);

}
}

Method 2:

public class SwapWithoutThirdVar
{
public static void main (String[] args) throws java.lang.Exception
 {
 String s1 = "one";            
 String s2 ="two";          
 s1=s2+s1;
 s2=s1.replace(s2,"");
 s1=s1.replace(s2,"");         
 System.out.println("S1 : "+s1); 
 System.out.println("S2 : "+s2);
  }
}

For Integers

public class SwapWithoutThirdVar {

public static void main(String a[]){
    int x = 10;
    int y = 20;       
    x = x+y;
    y=x-y;
    x=x-y;
    System.out.println("After swap:");
    System.out.println("x value: "+x);
    System.out.println("y value: "+y);
}
}
Krishnamoorthy
  • 1,236
  • 11
  • 17
0

You can do in this way.

public static void main(String[] args) {
        // TODO Auto-generated method stub

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

        System.out.println(a);
        System.out.println(b);

        a = a+b;
        b = "";

        System.out.println("*************");
         b = a.substring(0, 3);
         a = a.substring(3, 6);

         System.out.println(a);
         System.out.println(b);

    }
Aishu
  • 1,310
  • 6
  • 28
  • 52
0

package com.core;

public class SwappingNoTemp {

public static void main(String[] args) {

    String a = "java";
    String b = "c";

    a = a + b;

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

    System.out.println("swapping is a.." + a);
    System.out.println("swapping  is b.." + b);

}

}

0
String a = "one";//creates "one" object on heap
String b = "two";// creates "two" object on heap
System.out.printf("a is %s , b is %s%n",a,b);
a = "two";// will not create new "two" object & now a is pointing to "two" object
b = "one";// will not create new "one" object & now b is pointing to "one" object
System.out.printf("a is %s , b is %s%n",a,b);
Inderjeet
  • 9
  • 2
0

You can also do this by using a temp variable but in a different way:

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

temp=a.concat(b);
b=temp.substring(0,a.length());
a=temp.substring(a.length(),temp.length());

System.out.println("After Swapping A:"+a+"B:"+b);
Sandeep Kumar
  • 2,397
  • 5
  • 30
  • 37
0

I'd just like to point out, just in case anyone looks through this thread. There is no way of swapping two strings without using a third variable. In the java examples, since strings are immutable, a=a+b creates a third string, and doesn't reassign a. Doing the reverseString, creates a new variable, but this time on the stack frame as the program goes into a new scope. The use of Xor swapping might work, but Strings are immutable in java, and so xor swaps will also create a temporary variable. So in fact, unless the language enables you to reassign to the same memory space, it isn't possible to swap strings without creating new variables.

0

Swap with a multidimension assignment:

var a = "one";
var b = "two";
console.log("a =",a);
console.log("b =",b);
a = [b, b = a][0];
console.log("after swap a =",a);
console.log("after swap b =",b);
-1

For strings:

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

a = a + b;
b = a.replace(b, "");
a = a.replace(b, "");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jj Tuibeo
  • 773
  • 4
  • 18
  • 3
    Thats nice, if the strings are different. But if they are the same, you get problems. String a = "hello", String b = "ello" – Husman Aug 30 '13 at 09:09
-1
public class ex{
    public static void main(String[] args){

        String s1="abc";
        String s2="def";

        System.out.println(s1);
        System.out.println(s2);

        s3=s2.replaceAll(s1,s2=s1);

        System.out.println(s1);
        System.out.println(s2);

    }
}
Bless
  • 5,052
  • 2
  • 40
  • 44