Java Program To Swap Variables using Bitwise Operators
Here’s a Simple Program To Swap Variables using Bitwise Operators in Java Programming Language. This Java Program To Swap Two Numbers makes use of only Two Variables and doesn’t use any Third or Temporary Variable.
What are Bitwise Operators?
Bitwise Operators are specifically used in Digital Computer Programming. Such operators can be used to manipulate the Bits or Binary Digits in a given Integer. It works upon Byte-Level tasks that makes use of Bitwise Operators.
Example:
& represents Binary AND
| represents Binary OR
<< represents Binary Left Shift
^ represents Binary XOR
Also Read: Java Code To Swap Two Variables without using Temporary Variable
Java Program To Swap Two Variables using Bitwise Operators
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.io.*; import java.util.*; class SwapVariables { public static void main(String args[]) { int num1,num2; Scanner sc = new Scanner(System.in); System.out.println("Enter the First Number:"); num1 = sc.nextInt(); System.out.println("\nEnter the First Number:"); num2 = sc.nextInt(); System.out.println("\nBefore Swapping Variables\n"); System.out.println("A = " + num1 + "\nB = " + num2); num1 = num1^num2; num2 = num1^num2; num1 = num1^num2; System.out.println("\nAfter Swapping Variables\n"); System.out.println("A = " + num1 + "\nB = " + num2 + "\n"); } } |
Output

In case you have any doubt about Bitwise Operators or if you get any Compilation Errors in this Java Program To Swap Variables using Bitwise Operators, let us know about it in the Comment Section below.