17

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
Community
  • 1
  • 1
danmcardle
  • 2,079
  • 2
  • 17
  • 25

2 Answers2

13

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

Jeff Anderson
  • 799
  • 7
  • 18
Mechkov
  • 4,294
  • 1
  • 17
  • 25
  • 2
    +1 Good answer but here is a more direct link: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5304 – Ray Toal Nov 25 '11 at 17:55
  • 1
    Fair enough about the link. Thanks! – Mechkov Nov 25 '11 at 17:57
  • 1
    Saying "that's how they intended it to work" is different from answering the question of why it works that way. Can anyone give a justification for this decision? On the surface, the silent cast seems error-prone in a language that requires explicit casting everywhere else. – Eric Lindauer Mar 31 '13 at 20:40
  • @EricLindauer: I expect it works as it does because the arithmetic operators never give a result of any type smaller than `int` but Java wanted to allow `+=` to be usable on smaller types, and Java places a higher priority on making type conversion rules simple and "consistent", than on allowing things which make sense while disallowing things which are likely erroneous. – supercat Feb 10 '14 at 21:56
4

According to the Java language specification, section 15.26.2:

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);
Jörn Horstmann
  • 33,639
  • 11
  • 75
  • 118
Bhushan
  • 18,329
  • 31
  • 104
  • 137