In this tutorial, we will see different ways of swap two numbers in Java.
We will also see how to swap two numbers without using third variable.
Logic 1: Using third variable
package demopkg; public class SwapTwoNumbers { public static void main(String[] args) { int a = 10, b = 20; int t=a; // Using third variable t a=b; b=t; System.out.println("Value of a is: "+a + "\n"+"Value of b is: " +b ); } }
Output:
Value of a is: 20
Value of b is: 10
Logic 2: Using * and / operator without using third variable
package demopkg; public class Logic_2_Swap2Numbers { public static void main(String[] args) { // Logic 2- using * and / without third variable int a = 10, b = 20; a=a*b; //10*20=200 b=a/b; //200/20=10 a=a/b; //200/10=20 System.out.println("Value of a is: "+a + "\n"+"Value of b is: " +b ); } }
Logic 3: Using + and – operator without using third variable.
package demopkg; public class Logic_2_Swap2Numbers { public static void main(String[] args) { // Logic 2- using + and - without third variable int a = 10, b = 20; a=a+b; //10+20=30 b=a-b; //30-20=10 a=a-b; //30-10=20 System.out.println("Value of a is: "+a + "\n"+"Value of b is: " +b ); } }
Logic 4: Using XOR (^) Operator
package demopkg; public class Logic_2_Swap2Numbers { public static void main(String[] args) { // Logic 4- using bitwise XOR (^) operator int a = 10, b = 20; a=a^b; //10^20=30 b=a^b; //30^20=10 a=a-b; //30^10=20 System.out.println("Value of a is: "+a + "\n"+"Value of b is: " +b ); } }
Code Explanation:
In this logic, XOR operator converts decimal value into binary value then calculate it. So here value of a=10 converts into binary value which is 1010 and value of b=20 is become 10100.
Now if I am calculating a=a^b à 1010^10100 = 11110 (XOR operator return 1 for same value and 0 for different values)
Same like we can calculate other values.
Logic 5: Using Single statement
package demopkg; public class Logic_5_Swap2Numbers { public static void main(String[] args) { // Logic 5- Using Single statement int a= 10, b=20; b = a+b - (a=b); System.out.println("Value of a is: "+a + "\n"+"Value of b is: " +b ); } }
Code explanation:
Here calculation starts from right to left, so first calculated (a=b) means value of b assigned to a. Now value if a is 20. Then a+b calculated. Now it is 30
Now expression is like b = 30-20. So it becomes b=10 and a value is a=20.
Watch this Video:
Hope you have enjoyed this tutorial. Happy Learning 🙂
Must Read: