This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The compound assignment operators include an implicit cast. Therefore, this code:
Is really equivalent to:
The Bitwise Complement Operator (~), however, includes no such cast. Instead, it promotes the operand to an int and returns it. As you can't assign an int to a byte, you get an error. If you want to assign that value to your byte variable, you'll have to include your own cast.
The bitwise inversion operator ~ is applied to the value of x. The byte in x is widened to an int before being inverted. It's still an int after being inverted. To assign it to a byte you must use a cast to let the compiler know that you are aware of the possibility of loss of precision.