I spotted Java's +=, -=, *=, /= compound assignment operators (good question :)), but it had a part that I don't quite understand. Borrowing from that question:
int i = 5; long l = 8;
Then
i = i + l;
will not compile buti += l;
will compile fine.
The accepted answer to the linked question states that:
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.
which gives that i += l;
is the same as i = (int)((i) + (l));
with the exception that i
is only evaluated once.
A long
may be (IIRC even is guaranteed to be) longer than an int
, and thus can hold a much greater range of values.
Given that this situation can very easily cause data loss due to necessary narrowing conversion at some point during execution of the statement (either r-value expression evaluation, or assignment), why is i += l;
not a compile-time error or at least warning?
i = (int)(i + l);
, if the type of i is int. – Yarak