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

后端 未结 18 803
梦谈多话
梦谈多话 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:21

    // 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.

提交回复
热议问题