Single line expressions to swap two integers in Java
Given two integers, swap them in a single line in Java.
There are several expressions to swap two variables in a single line in Java:
1. Using Bitwise XOR (^) Operator
|
1 2 3 4 5 6 7 8 9 10 11 |
class Main { public static void main (String[] args) { int x = 5, y = 10; x = x ^ y ^ (y = x); System.out.println("Values of x and y after swapping are " + x + " and " + y); } } |
2. Using Addition and Subtraction Operator
|
1 2 3 4 5 6 7 8 9 10 11 |
class Main { public static void main (String[] args) { int x = 5, y = 10; x = x + y - (y = x); System.out.println("Values of x and y after swapping are " + x + " and " + y); } } |
3. Using Multiplication and Division Operator
|
1 2 3 4 5 6 7 8 9 10 11 |
class Main { public static void main (String[] args) { int x = 5, y = 10; x = (x * y) / (y = x); System.out.println("Values of x and y after swapping are " + x + " and " + y); } } |
It is worth noting that we can also use all the above-discussed methods with C/C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)