Jump to content

I need some help in Java Assignment operator!


Recommended Posts

Those are bitwise assignment operators. They perform a bitwise operation and then assign the result to a variable.

It looks like the W3Schools Java tutorial does not have any information about how bitwise operators work, probably because it is difficult to explain in simple terms.

Bitwise operators treat whole numbers as sequences of 1s and 0s. Each 1 or 0 is called a bit. There are several operations you can do with bits, which are mostly similar to the logical operators. There is & (and), | (or), ~ (not), ^ (exclusive or), << (shift left) and >> (shift right).

The sequences of 1s and 0s are called binary representations of the numbers. For example, 5 in binary is 101 and 3 in binary is 011.

& operator

  • Decimal: 5 & 3 = 1
  • Binary: 101 & 011 = 001

| operator

  • Decimal: 5 | 3 = 7
  • Binary: 101 | 011 = 111

~ operator (Since integers have 32 or 64 bits, and all the zeroes need to be taken into account, and computers treat large binary numbers beginning with 1 as negative, this one is actually more complicated to describe)

  • Decimal: ~5 = -6
  • Binary: ~00000000000000000000000000000101 = 11111111111111111111111111111010

^ operator

  • Decimal: 5 ^ 3 = 6
  • Binary: 101 ^ 011 = 110

<< operator Moves bits a certain number of positions to the left (This is equivalent to dividing by 2 a number of times and removing any decimal part from the result)

  • Decimal: 5 << 2 = 20
  • Binary: 101 << 2 = 10100

>> operator Moves bits a certain number of positions to the right (This is equivalent to multiplying a number by 2 a number of times)

  • Decimal: 5 >> 2 = 1
  • Binary: 101 >> 2 = 001
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...