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.

So

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


is equivalent to

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


http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.2
Fascinating! It's fun learning something new. :)

2 comments:

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".