Core Java

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 1Element 2Element 1 ^ Element 2
000
011
101
110

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.

xor operator in java

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 as 1010
  • In Binary format – 20 is represented as 10100
  • 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.

Download
You can download the full source code of this example here: Java XOR Operator Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button