Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

XOR assignment operator (^=)

The ^= operator stores an XOR result in its left operand. It works with integral types and boolean; it does not mean exponentiation.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

variable ^= expression;

variable ^= expression computes XOR and stores the result in variable. For integers, a result bit is 1 when the corresponding bits differ. A mask toggles the bits selected by its ones; applying it again restores the value.

For boolean, the result is true when the values differ. Boolean XOR does not perform numeric promotion; boxed Boolean operands are unboxed to boolean as needed. There is no short-circuit evaluation: the right operand is evaluated after successfully reading the left operand. Neither ^ nor ^= means exponentiation.

E1 ^= E2 corresponds to E1 = (T) ((E1) ^ (E2)), where T is the type of E1, except that E1 is evaluated only once. For integral operands, binary numeric promotion precedes XOR; implicit conversion of the result back to T can discard high-order bits. Thus byte b = 1; b ^= 2; is valid, whereas b = b ^ 2; requires a cast.

Examples

public class Main {
    public static void main(String[] args) {
        byte flags = 0b1010;
        int mask = 0b0110;
        flags ^= mask;
        System.out.println(flags);
        flags ^= mask;
        System.out.println(flags);

        boolean enabled = true;
        enabled ^= true;
        System.out.println(enabled);
    }
}

Result

12
10
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources