What does ^ mean in Java with examples

In this post, I will be sharing what does ^ mean in Java with examples. ^ is also known as bitwise exclusive OR or XOR operator in Java.

Read Also: What does ? mean in Java with examples

Bitwise exclusive OR operator(^) is used to perform operations on individual bits of a number. Hence, it is classified into bitwise operators.

Let's dive deep into the topic:

What does ^ mean in Java with examples

According to Oracle docs, It takes two boolean operands and returns true if they are different, otherwise returns false if both operands are the same.

Note: The Bitwise exclusive OR (XOR) operator is denoted by the caret(^) symbol.


The truth table for the XOR operator is shown below:

Bitwise exclusive OR operator

From the above table, we can conclude that the XOR operator returns false if both operand's values are the same, otherwise, it returns true.

Syntax
 (operand1 ^ operand2) 

Example of XOR(^) Operator example

 25 = 00011001  (In Binary)
30 = 00011110  (In Binary)

Bitwise Exclusive OR operation of 25 and 30

   00011001
 ^ 00011110
 ----------------
   00000111 (= 7 in Decimal)

Java Program for ^ bitwise exclusive OR operator

 public class BitwiseExclusiveOR {
    public static void main(String args[]) {
      int num1 = 25;
      int num2 = 30;
      int result = num1 ^ num2;
      System.out.println("num1 ^ num2 = " + result);
    }
}


Output:
num1 ^ num2 = 7

In the above Java program, we have defined two XOR operands 25 and 30. After performing the XOR operation we get the result 7.

Where we can use the XOR operator

Given below are some scenarios where we can use the XOR operator in Java:

1. Swapping values without using a temporary variable.
2. Finding the missing number in the given range from 1 to n.

That's all for today, please mention in the comments in case you have any questions related to what does ^ mean in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry