about += and distinct data types
Hi, well, Im surprised today as I found out that:
int total = 0;
long amount = 200;
total += amount;
does compile!(I don't like that), but the following does not
int total = 0;
long amount = 200;
total = total + amount;
I tought "a+=" was equivalent to "a=a+". It is not this way? Thanks.
I'm using jdk 1.6 u1, if it is a bug of the compiler i would be surprised too.
Actually "X op= Y" is equivalent to "X= (type-of-X) (X op Y)" -- there is an implicit cast.
This can create subtle bugs. You might expect the following code to assign the number 127 to the variable b but it doesn't:
byte b = -1;
b >>>= 1; // unsigned shift left
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26
Assignment Operatrors
15.26.2 Compound Assignment Operators
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
jverda at 2007-7-12 21:35:21 >
