Java XOR Operator Example
Hello readers, in this tutorial, we will explain the Java XOR operator. We’ll cover the XOR symbol that is an operator that falls under the Bitwise category.
1. Introduction
Java programming offers Operators that are used to perform various operations in Java.
1.1 XOR operator in Java
The XOR
operator is denoted as ^
in the programming language and works on bits of numbers (i.e. 0
or 1
). It returns true if either of the bits in an operand is a 1
. Following table summarizes the XOR
operations –
Element 1 | Element 2 | Element 1 ^ Element 2 |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
To start with the captioned tutorial, we are hoping that users at present have their preferred Ide installed on their machines. For easy usage, I am using Eclipse Ide on a Windows operating system.
2. Java XOR Operator Example
In this example, we’ll demonstrate the XOR
operator in java. For a better understanding, developers can execute the below code in Eclipse Ide.
Example.java
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | package com.jcg; public class Example { // Bitwise XOR Operator - Such that either of the bits in an operand is '1', then the resultant bit is '1'. public static void main(String[] args) { int ele1 = 10 ; // Binary format= 1010 int ele2 = 20 ; // Binary format= 10100 // Bitwise XOR // 1010 ^ 10100 = 11110 = 30 System.out.println( "XOR Result= " + (ele1 ^ ele2)); } } |
If everything goes well, the following output will be printed in the Ide console.
Output
1 | XOR Result= 30 |
2.1 Output Explanation
In here,
- In Binary format –
10
is represented as1010
- In Binary format –
20
is represented as10100
- According to the above table, we will get
11110
as a result - The
println()
method will print the decimal equivalent of the result
That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
3. Summary
In this tutorial, we learned the XOR
operator in Java. We covered the XOR symbol that is an operator that falls under the Bitwise category.
You can download the sample application as an Eclipse project in the Downloads section.
4. Download the Eclipse Project
This was an example of XOR in Java programming language.
You can download the full source code of this example here: Java XOR Operator Example