Low Orbit Flux Logo 2 F

Java How To Use Xor Operator

Java supports the use of the XOR operator both for bitwise operations and for logical operations.

Java Bitwise XOR Operator

To perform a bitwise XOR operation in Java you would use this operator: ‘^’. It would look like this:


5 ^ 7;

You can convert an int to a string that represents the binary digits in the number with this method:


Integer.toBinaryString(5)

Here are some examples showing you can apply the bitwise XOR operator to different numbers.


System.out.println( Integer.toBinaryString(5));    // 101
System.out.println( Integer.toBinaryString(7));    // 111
System.out.println( Integer.toBinaryString(10));   // 1010
System.out.println( Integer.toBinaryString(100));  // 1100100
System.out.println( "Result: " + Integer.toBinaryString(5 ^ 7));    // 10
System.out.println( "Result: " + Integer.toBinaryString(5 ^ 10));   // 1111
System.out.println( "Result: " + Integer.toBinaryString(10 ^ 100)); // 1101110

Java Logical XOR

This will only return true when one operand is true and the other is false. If they are both true or both false then it will return false.

Here is an example showing how this works:


if ( true ^ false )
    System.out.println("one true, one false");
if ( true ^ true )
     System.out.println("both true");
if ( false ^ false )
    System.out.println("both false");

The output will look like this:


one true, one false

Here is another example. The output will be the same.


if ( (5 == 5) ^ (4 == 3) )
    System.out.println("one true, one false");
if ( (5 == 5) ^ (4 == 4) )
    System.out.println("both true");
if ( (5 == 2) ^ (4 == 3) )
    System.out.println("both false");