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

后端 未结 18 1134
梦谈多话
梦谈多话 2021-02-02 12:30

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         


        
18条回答
  •  野的像风
    2021-02-02 13:25

    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.

提交回复
热议问题