In Java, when you do
int b = 0;
b = b + 1.0;
You get a possible loss of precision error. But why is it that if you do
int b = 0;
b += 1.0;
There isn’t any error?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That’s because
b += 1.0;is equivalent tob = (int) ((b) + (1.0));. The narrowing primitive conversion (JLS 5.1.3) is hidden in the compound assignment operation.JLS 15.26.2 Compound Assignment Operators (JLS Third Edition):
This also explains why the following code compiles:
But this doesn’t:
You need to explicitly cast in this case:
It’s worth noting that the implicit cast in compound assignments is the subject of Puzzle 9: Tweedledum from the wonderful book Java Puzzlers. Here are some excerpt from the book (slightly edited for brevity):
The last paragraph is worth noting: C# is a lot more strict in this regard (see C# Language Specification 7.13.2 Compound assignment).