Logical Operator ^ (XOR) Tutorial

In Java, the ^ (XOR) logical operator compares two or more conditional expressions and returns true if exactly one of the conditional expressions evaluates to true. The ^ is also a bitwise operator, but this tutorial will not cover that functionality. I rarely use this operator, but there was this circumstance a long time ago where I was using it and a funny thing popped into my head. The way this operator functions reminded me of the old Duck-Duck-Goose game I played as a kid. I know - it's really corny, but there can be only one Goose and any number of Ducks. When the Goose is named, the kids start to run. Just like that silly game, there can be only one True evaluation and any number of False evaluations. As long as exactly one conditional expression evaluates to True, the code block will run.

System.out.println( (5==5) ^ (5==6)); // displays true
System.out.println( (5==5) ^ (6==6)); // displays false
System.out.println( (4==5) ^ (5==6)); // displays false
System.out.println( (5==5) ^ (5==6) ^ (6==7) ^ (7==8)); // displays true
System.out.println( (5==6) ^ (6==7) ^ (7==7) ^ (7==8)); // displays true
System.out.println( (5==5) ^ (6==6) ^ (7==8) ^ (8==9)); // displays false



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md XOR
C:\Java>cd XOR
C:\Java\XOR>Notepad XOR.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class XOR {
    public static void main(String args[]) {
        System.out.println( (5==5) ^ (5==6)); // displays true
        System.out.println( (5==5) ^ (6==6)); // displays false
        System.out.println( (4==5) ^ (5==6)); // displays false
        System.out.println( (5==5) ^ (5==6) ^ (6==7) ^ (7==8)); // displays true
        System.out.println( (5==6) ^ (6==7) ^ (7==7) ^ (7==8)); // displays true
        System.out.println( (5==5) ^ (6==6) ^ (7==8) ^ (8==9)); // displays false   
        System.out.println();

        boolean duck = false;
        boolean goose = true;
    
        if (duck ^ duck ^ duck) {
            System.out.println("Did three ducks run?");
        }
        if (duck ^ duck ^ goose) {
            System.out.println("duck duck goose ran");
        }
        if (duck ^ goose ^ goose) {
            System.out.println("can\'t have two geese in this game");
        }

    }
}

Now switch back to the command prompt (CMD) and type in javac XOR.java and press Enter.
Now type in java XOR and press Enter.


C:\Java\XOR>javac XOR.java
C:\Java\XOR>java XOR
true
false
false
true
true
false

duck duck goose ran


Final thoughts

There is not much to learn when it comes to the ^ logical operator, just remember that you can have only one and only one True evaluation result for the entire outcome to result True.


Tutorials