Here is the question: write a method that swaps two variables. These two variables should be primitives. It doesn't need to be generic e.g. two int
variables. Is there a way?!
Two variables can be swapped in one line in Java. This is done by using the given statement. x = x ^ y ^ (y = x); where x and y are the 2 variables.
In order to swap elements of ArrayList with Java collections, we need to use the Collections. swap() method. It swaps the elements at the specified positions in the list.
While it is not possible to write a function that simply swaps two variables, it is possible to write a helper function that allows you to:
That's how you could do it:
int returnFirst(int x, int y) { return x; } int a = 8, b = 3; a = returnFirst(b, b = a); // try reading this as a = b; b = a; System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8
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:
b
is evaluated in order to be passed as the first argument to the functionb = a
is evaluated, and the result (the new value of b
) is passed as the second argument to the functionb
and ignoring its new valuea
If returnFirst
is too long, you can choose a shorter name to make code more compact (e.g. a = sw(b, b = a)
). Use this to impress your friends and confuse your enemies :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With