Possible Duplicate:
Varying behavior for possible loss of precision
Code Sample A
public class Test {
public static void main(String[] args) {
int i = 0;
i = i + 1.5;
}
}
Code Sample B
public class Test {
public static void main(String[] args) {
int i = 0;
i += 1.5;
}
}
Unsurprisingly, compiling A produces the error below. Surprisingly, compiling B produces no error and it appears to behave as if I inserted an explicit cast to integer before the double value 1.5. Why in the world does this happen? This goes against everything I thought I knew!
Test.java:6: possible
loss of precision
found : double
required: int
i = i + 1.5;
^
1 error
It is working as designed. The compound operators add an implicit cast to the operation. Otherwise you have to use an explicit cast.
More info?
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2