How to exchange the value of two variables in Java?

Asked

Viewed 10,429 times

9

You can create a Java function that changes the value of two variables without having to declare a temporary variable?

For example:

int a = 8, b = 3;
if(a > b) {
    // algo aqui, sem declarar uma variável "tmp"
}
// agora a deve valer 3 e b deve valer 8

In other languages, such as C++ and C#, it would be possible to pass the parameters by reference, but Java does not have this feature.

5 answers

12

As can be seen here it is impossible to make a method swap, the traditional way (passing the values by reference), in Java, since Java only accepts pass by value.

However, several solutions are proposed. As one of the proposed answers, it is possible to use a auxiliary function. However, you can create a swap method for lists or vectors, as proposed in the original solution.

If you do not want to create a method, it is possible to perform a XOR:

a = a^b;
b = b^a;
a = a^b;

based on that property.

  • 1

    "it is impossible to make a method swap in Java" It is good to clarify: impossible in the sense of the method - as a side effect - make the value of a go to the address/pointer/reference of b and vice versa. Because the only way to assign a simple reference in Java is through an operator in the very context of the method where it is declared.

  • @mgibsonbr, well noted, in case it is impossible to make a swap the traditional way (using the values passed as reference). I will edit the answer to make it more appropriate.

7

It is possible to use an auxiliary function like this:

int returnFirst(int x, int y) {
    return x;
}
int a = 8, b = 3;
a = returnFirst(b, b = a); // Leia como a = b; b = a;
System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8

Using the returnFirst function, we have a solution that meets almost all requirements:

  1. The exchange of values is done in only one statement;
  2. No need to declare a temporary variable (does not pollute caller code);
  3. Does not allocate temporary objects;
  4. With some overloads, being one of them with a Generic <T>, works for any type;
  5. The implementation of the auxiliary is trivial;
  6. Does not use tricks that only work integer numbers (such as XOR).

The specification of the Java language (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) ensures that the value of b is evaluated and passed before being overwritten by the assignment b = a in the second argument, unlike other languages (as I recall, C and C++ are not at all friendly and do not guarantee any order of evaluation of the arguments, only ensure that they will all be evaluated before the function starts to perform, obviously).

If you choose a short name like r1, is very easy to read

a = r1(b, b = a);

as if it were

a = b; b = a;

(although in fact b = a perform first)

6

If your variables are integer, you can use the XOR trick:

int a = 8, b = 3;
if(a > b) {
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
}
// agora a deve valer 3 e b deve valer 8
  • 1

    Hehe, to be honest I’m taking advantage that the site is new to answer my own question with a trick that I found more cool than XOR :-)

  • 1

    @Interesting stuff, +1

  • No problem, I don’t intend to do this often. The answer is my own, so it’s OK.

  • I had read the rules and saw that I could, but it seems that people don’t really like "self-response", haha :-)

  • In fact, to be complete: link to my original answer in English: http://stackoverflow.com/questions/1363186/is-it-possible-to-write-swap-method-in-java/16826296#16826296

6

The easiest way is to add the two variables together and then subtract by the initial value of the other. That way:

int a= 8, b = 3;
a =  a + b;
b = a - b;
a = a - b;
  • 1

    This is a good alternative to XOR, when restricted to integers (and when the default behavior in case of overflow is "ignore" - as is the case of Java)

1

import java.util.Scanner;

public class Troca {
    int a;
    int b;
    int aux;

    public int trocaA(){
       this.aux = this.b;
    return this.aux;
   }
    public int trocaB(){
       this.b = this.a;
    return this.a;
    }
    public void mostrar(){
        System.out.println("\n|-----------------|");
        System.out.println("| 1º Valor era: "+this.a+" |\n| Agora vale: "+trocaA()+"   |");
        System.out.println("|-----------------|");
        System.out.println("| 2º Valor era: "+this.b+" |\n| Agora vale: "+trocaB()+"   |");
        System.out.println("|-----------------|");

}
    public static void main(String[] args) {
        Troca tr = new Troca();
        Scanner ent = new Scanner(System.in);
        System.out.println("1º Valor: ");
        tr.a = ent.nextInt();
        System.out.println("2º Valor: ");
        tr.b = ent.nextInt();

        tr.mostrar();

    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.