Swapping of Two Numbers in Java Using XOR

Java xor operator. The source code for a Java program that uses the Bitwise XOR operation to swap the contents of two numbers. As input, choose any two integer numbers.

Then we discover the bitwise XOR of the first and second variables and store the result in the first variable. We repeat the bitwise XOR operation on the same variables and save the result in the second variable.

import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
int m, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number");
m = s.nextInt();
System.out.print("Enter the second number");
n = s.nextInt();
m = m ^ n;
n = m ^ n;
m = m ^ n;
System.out.println("After Swapping the number");
System.out.println("First number:"+m);
System.out.println("Second number:"+n);
}
}

Output:

Enter the first number 45
Enter the second number 56
After Swapping the number
First number: 56
Second number: 45

Bitwise to Execute Java XOR Operator

A bitwise operator is an operator that manipulates individual bits in bit patterns or binary numerals to execute bitwise operations. In communication stacks, where the individual bits in the header attached to the data represent crucial information, bitwise operators are utilized.

Checking if an integer is even or odd is another technique you can do using bitwise operator in java. Let’s see what we can come up with. The idea behind! is that the binary representation of 1 is 0001, and the least significant bit’s place value is 1.

Bitwise Operator and Logical Operator

To begin, logical operators operate on boolean expressions and return boolean values (true or false), whereas bitwise operators operate on binary digits of integer values (long, int, short, char, and byte) and return an integer value.

How Bitwise Operators are Faster

It is a quick and simple action that is fundamental to higher-level arithmetic operations and is provided directly by the CPU.

Xor Operator in Java

The exclusive or logical operation accepts two boolean operands and returns true only if and only if they are different. As result, if the two operands have the same value, it returns false. So, when we need to check for two conditions that can’t both be true at the same time, we can use the XOR operator.