Most people know of the compound assignment operators, such as +=, -=, <<=, and others. It is generally thought that these compound operators can be broken into simple operators like this:
x += y is equivalent to x = x + y
x -= y is equivalent to x = x - y
etc.
However, although this is pretty close, it doesn't tell the whole story. What happens if you compile and execute this code?
|
byte b = 10; b = b + 5; |
|
byte b = 10; b += 5; |
The reason this works is because the compound assignment operator isn't exactly equivalent to what we showed above. Instead, the compound assignment operator includes an implict cast to the type of the left-hand operand. So, if we were to break apart the compound operator, it would look like this:
b += 5 is equivalent to b = (byte)(b + 5)
Because of the implicit cast, the compiler doesn't complain about this line. With that in mind, you need to be aware that a compound assignment operator will allow you to overflow variables without giving you any sort of warning. What does the following print?
|
byte b = 10; b += 130; System.out.println(b); |
The output of that code is -116. We lost some data because the compound assignment operator includes an implicit cast and the compiler never warned us that we were doing something dangerous. Keep that in mind.
You can read all about compound assignment operators in the JLS §15.26.2 Compound Assignment Operators.
Corey
byte b = 5;
b =+ 5;
Is exactly the same as writing this:
b = 5;
if I have int a=1,b=2,c=3; a+=b+=c+=7; what is the equiv statment that is fully parenthesized? and what are the values for a,b,c. Thanks for any help
To me, that looks like a homework problem and I can't say I want to answer people's homework for them. I will, however, say that the values for a, b, and c are easily determined by simply compiling and executing the code. Given that, work backwards and work out what the parenthesized equation would be.
