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)