Wednesday, November 10, 2010

Learned something new today...

When I was stumped, a co-worker found the answer:
According to the JLS:

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.


int x = 0;
x += Math.pow(y,z);

is equivalent to

int x = 0;
x = (int) (x + Math.pow(y,z));
Fascinating! It's fun learning something new. :)


Rhiannon said...

And my comment is o_O

noricum said...

What it means is that the following works:

int x = 1;
double y = 3.14;
x += y;

where you might think it should complain about "possible loss of precision".