2

I teach Computer Science AP and we use java to teach programming concepts. One thing my students and I have noticed is that the following code gives a Loss of precision error:

int j = 0;
j = j + 4.0;

however this code does not:

int j = 0
j += 4.0;

To me, these are the same thing. I have searched for some posting to answer this but could not find anything If you have a link to a post that explains this, my students and I would appreciate it. Thanks!

HavelTheGreat
  • 3,299
  • 2
  • 15
  • 34
  • See [here](http://stackoverflow.com/questions/8710619/java-operator). โ€“ TNT Mar 12 '15 at 12:57
  • This might help [Java += operator](http://stackoverflow.com/questions/8710619/java-operator) โ€“ Ben Win Mar 12 '15 at 12:57
  • If you teach CS, you may be interested in the new [CS Educator's Stack Exchange](http://cseducators.stackexchange.com) (though since it's still in private beta, it's easiest to enter [through here](https://area51.stackexchange.com/proposals/92460/computer-science-educators)) โ€“ Ben I. Jun 02 '17 at 19:25

3 Answers3

1

That's because the expression:

j += 4.0;

is equivalent to:

j = (int) (j + 4.0);

Check JLS ยง 15.16.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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

It is because += is a Compound Assignment Operator, which makes an implicit cast required to not throw the error. Without it, you are adding two different primitive data types without any implicit or explicit cast. Essentially, the += technique is equivalent to :

j = (int)(j + 4.0);

This question may further explain the += operator to you and your students.

Community
  • 1
  • 1
HavelTheGreat
  • 3,299
  • 2
  • 15
  • 34
0
j+=4.0

Is the same as

j = j + (int)4.0

So the compiler automatically adds the cast for you in that situation. In the first example, it does not.

Marcus Widegren
  • 544
  • 2
  • 8