JavaDeveloper
JavaDeveloper

Reputation: 5660

What does ^= mean in Java?

I have seen the following code in HashMap.java.

    h ^= k.hashCode();
    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);

A few random inputs produced an output similar to addition, but following code resulted in 0

   int p = 10;
    p ^= 10;
    System.out.println("_______ " + p);

Upvotes: 1

Views: 362

Answers (5)

Birkan Cilingir
Birkan Cilingir

Reputation: 488

^= is bitwise exclusive OR and assignment operator. x ^= 2 is same as x = x ^ 2.

Upvotes: 1

user2030471
user2030471

Reputation:

It is a compound assignment operator in java:

x op= y is equivalent to x = x op y (loosely speaking, see above link).

For example:

x += y; is equivalent to x = x + y;

x -= y; is equivalent to x = x - y;

and so on ...


For reference, this is the complete list of all such operators in java:

+= -= *= /= &= |= ^= %= <<= >>= >>>=

Upvotes: 1

Luke Briggs
Luke Briggs

Reputation: 3789

^ is the symbol for a logical XOR (Exclusive OR).

When placed before an equals sign, this means 'XOR myself with the given value, and write the result back to myself'. a ^= value is the same as saying a = a ^ value.

It might make it clearer if done with other operators, such as add:

E.g:

int counter = 14;

 // Add 20 to counter (could also be written counter = counter + 20):
counter += 20;

// Counter is now 34

Upvotes: 1

Sage
Sage

Reputation: 15418

^ is known as XOR (Exclusive disjunction or exclusive or), a logical operator, which follows:

1 xor 1 = 0
1 xor 0 = 1
0 xor 1 = 1
0 xor 0 = 0

as p^=10 is equivalent to:

p = p ^ 10; or,  p = p xor 10

with p = 10 your operation is simply: , (10 ^ 10), which will result in 0

Upvotes: 1

Joe Bane
Joe Bane

Reputation: 1646

The ^= operator does an XOR with the variable on the left and the operand, then does an assignment to that variable of the result.

XOR something with itself and you get zero. It is an efficient way to set a register to zero as it doesn't move any memory.

Upvotes: 4

Related Questions