How to change the value of two variables in Java?

8

Is it possible to create a function in Java 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.

    
asked by anonymous 04.02.2014 / 13:04

5 answers

11

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

However, several solutions are proposed. As one of the suggested answers, you can use an helper 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, you can do XOR :

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

based on this property .

    
04.02.2014 / 13:11
6

You can 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:

  • Values are exchanged in just one statement;
  • It is not necessary to declare a temporary variable (it does not pollute the caller code);
  • Do not allocate temporary objects;
  • With some overloads, one of them with generic <T> , works for any type;
  • Auxiliary implementation is trivial;
  • Does not use tricks that only work whole numbers (like XOR).
  • The Java language specification ( 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, they only guarantee that they will all be evaluated before the function starts to run, obviously).

    If you choose a short name like r1 , it's pretty easy to read

    a = r1(b, b = a);
    

    As if it were

    a = b; b = a;
    

    (although actually b = a run first)

        
    04.02.2014 / 13:07
    5

    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
    
        
    04.02.2014 / 13:06
    5

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

    int a= 8, b = 3;
    a =  a + b;
    b = a - b;
    a = a - b;
    
        
    04.02.2014 / 13:38
    -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();
    
        }
    }
    
        
    10.04.2018 / 19:56