Java XOR3 May 2025 | 5 min read Java XOR is one of the Bitwise operators available in Java. The XOR ( aka exclusive OR) takes two boolean operands and returns true if they are different. The best use case of the XOR operator is when both the given boolean conditions can't be true simultaneously. In addition to its use with boolean values, the XOR operator is also frequently applied to integer values at the bit level. Let's understand what the bitwise operators are in Java? Bitwise Operators in JavaAn operator is a symbol that is defined to perform a specific operation. For example, operator '+' is used to add two values. Just like traditional operators, Java provides supports for bitwise operators. These operators are used to perform operations on individual bits of a number. That is why these operators are called bitwise operators. It is evaluated from left to right. The bitwise operators can be used with any of the integral data types such as int, char, short, etc. Usually, the bitwise operators are used while performing manipulation or query operations over the binary indexed tree. There are seven types of the bitwise operator in Java that are used to perform bit-level operations:
In this section, we will discuss the Bitwise XOR operator in Java. See all Bitwise Operator in Java. Java XOR Operator (Exclusive OR)The XOR operator is denoted by a carrot (^) symbol. It takes two values and returns true if they are different; otherwise returns false. In binary, the true is represented by 1 and false is represented by 0. Below is the truth table of the XOR operator:
From the above table, we can see it returns true if and only if both operand's values are different. Otherwise, it returns false. Let's understand it with an example: Example of XOR OperatorConsider the following example: TestXor.java Output: x ^ y = 2 Explanation Using the bitwise XOR operator on two integer values is demonstrated in the Java code that is provided. Two numbers, x and y, are declared and initialised to 5 and 7, respectively, in the main() method of the TestXor class. Next, these integers undergo the bitwise XOR operation. Five is 0101 in binary representation, while seven is 0111. Every corresponding bit of the two numbers is compared using the XOR operation that gives 1 if the bits are different and 0 otherwise. Therefore, 0101 ^ 0111 yields 0010, or 2 in decimal notation. The output of the XOR operation is System.out.println("x ^ y = " + (x ^ y));, that prints x ^ y = 2 to the console. Some Other Use Cases and Examples1. Swapping Values without a Temporary VariableXOR can be used to swap two values without using a temporary variable. SwapUsingXOR.java Output: Before swap: a = 10, b = 15 After swap: a = 15, b = 10 Explanation The provided Java code demonstrates an efficient technique to swap the values of two integer variables using the XOR bitwise operator without the need for a temporary variable. Initially, the variables a and b are set to 10 and 15, respectively. The XOR operation is then applied in three steps: first, a is updated to the result of a XOR b, which changes a to 5. Next, b is updated to the result of the new a XOR b, which simplifies to the original value of a, now making b equal to 10. Finally, a is updated to the result of the new an XOR b, which simplifies to the original value of b, now making an equal to 15. This sequence effectively swaps the values of a and b. The output confirms the swap, showing that a is now 15 and b is now 10. This method leverages the XOR operator's properties, where each bit comparison results in 1 if the bits are different and 0 if they are the same, making it a clever and efficient approach to value swapping. 2. Checking for Odd or Even NumbersThe least significant bit of an integer determines whether it is odd or even. CheckOddEven.java Output: 9 is odd Explanation The provided Java code demonstrates how to determine if a given integer is odd or even using the XOR bitwise operator. The main() method initializes an integer variable num with the value 9. The code then uses an if statement to check if the result of num XOR 1 is equal to num + 1. For an odd number, flipping the least significant bit (which is 1) with XOR 1 results in the next higher even number, making the condition true. Conversely, for an even number, flipping the least significant bit (which is 0) results in the next lower odd number, making the condition false. In this case, since 9 is odd, 9 XOR 1 equals 10, which is indeed 9 + 1, so the program prints "9 is odd". If num were even, the program would print "num is even". ConclusionJava's XOR operator is an effective tool for bitwise and logical computations. It is helpful in situations when it is necessary to evaluate mutually exclusive conditions because it returns true when two boolean operands are distinct. When XOR is used on integers, it does bitwise comparisons, setting resultant bits to 1 in cases where the operands' corresponding bits differ. This feature is very helpful for a variety of programming tasks, such as data processing, encryption, and binary representation problem-solving. Writing efficient and effective Java code is improved by knowing and using bitwise operators, such as XOR, as shown in the TestXor example, which uses the XOR operation to compare and alter binary values of integers. |
Reverse engineering is a critical process in software development that allows developers to gain valuable insights into existing codebases. It enables them to understand complex systems, identify design patterns, and improve maintainability. One powerful tool in the arsenal of reverse engineering is ArgoUML, a popular open-source...
3 min read
In Java, Scanner is a class that provides methods for input of different primitive types. It is defined in java.util package. In this section, we will learn how to take multiple string input in Java using Scanner class. We must import the package before using the Scanner...
3 min read
Creating stable and responsive apps in the dynamic world of Java development requires effective task management. Java concurrency can be achieved using asynchronous programming and multithreading. Multithreading in Java Programming's notion of multithreading allows for the simultaneous operation of several threads inside a single program. Writing programs that...
5 min read
A positive integer array with an equal amount of digits for each integer is given. The number of distinct digits that occur in the same location in two integers is known as the digit difference between them. The total of the digit differences between each pair of...
7 min read
A File in Java abstractly represents a path to a file or directory. Because it enables developers to deal with file paths and operations without having to interact with the underlying file system directly until necessary, this abstraction is essential. Many Java applications frequently require...
4 min read
The FileInputStream class of the Java programming language is used to read data from files in a byte-oriented fashion. It has several data reading methods, including read(), read(byte[]), and read(byte[], int, int). Finalise(), a method that the FileInputStream class inherits from the Object class, is one...
4 min read
The conversion of N-ary trees to binary tree serves as a standard computer science operation for reducing hierarchy complexity while maintaining hierarchical structures. An N-ary tree allows each node to have multiple children, making it complex to manage using standard tree structures. To efficiently represent an N-ary...
5 min read
LinkedHashMap is a pre-defined class in Java programming that can be extended from HashMap. It gives the hash table a consistent order of iterations. The java.util package contains LinkedHashMap, which is used to maintain double-linked lists. Syntax: LinkedHashMap<K, V> map = new LinkedHashMap<>(initialCapacity, loadFactor, accessOrder); Parameters: K:...
3 min read
In Java, Future is an interface that belongs to java.util.concurrent package. It is used to represent the result of an asynchronous computation. The interface provides the methods to check if the computation is completed or not, to wait for its completion, and to retrieve the...
24 min read
Problem Description Envision yourself harvesting fruits from a row of interconnected fruit trees. Every tree yields a certain kind of fruit. There are two baskets that you have, and each basket has an infinite capacity to carry a single variety of fruit. You select fruits from any...
6 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India