
Not All Assignments are Created Equal
January 30, 2007Many introductory Java books will tell you that the compound assignment operators (e.g. b += 1) are just a shorthand for doing an assignment where something is assigned the result of itself involved in some arithmetic operation (e.g. b = b + 1). In this article we’ll see that the difference between compound operators and their supposed expanded versions can be the difference between running and failing to compile.
These are supposed to be equivalent right?
byte b1 = 0;
b1 = b1 + 1;
byte b2 = 0;
b2 += 1;
Well, that’s what a lot of books will tell you. For many cases they’re very close to equivalent and it’s certainly a fair way to describe them to a junior programmer that is just being exposed to compound operators for the first time. Once you start studying for the Sun Certified Java Programmer (SCJP) test or just dig a little deeper into the language you find that there is a subtle, yet important difference.
This will not compile:
byte b1 = 0;
b1 = b1 + 1;
Why not? It looks pretty straightforward. The reason lies in how Java handles integer arithmetic. All integral expressions in Java result in at least an int. That means that if the operations involve a long they’ll result in a long, but if they involve ints, shorts or bytes (the integral types that are smaller than a long) they will still result in an int. Since an int does not fit in a byte, it fails at compile time.
On the other hand, this compiles fine:
byte b2 = 0;
b2 += 1;
So why does that work? Isn’t it pretty much the same thing as the code above that won’t compile? It turns out that Java inserts an implicit cast when the compound operator is used. The compound assignment is actually translated to something like this:
byte b2 = 0;
b2 = (byte)(b2 + 1);
The implicit cast handles the problem of narrowing that comes from assigning an int (32 bits) to a byte (8 bits).
Joshua Smith
Not that I’m impressed a lot, but this is more than I expected when I found a link on Digg telling that the info here is awesome. Thanks.