Java Language Specification defines E1 op= E2
to be equivalent to E1 = (T) ((E1) op (E2))
where T
is a type of E1
and E1
is evaluated once.
That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.
public class PlusEquals {
public static void main(String[] args) {
byte a = 1;
byte b = 2;
a = a + b;
System.out.println(a);
}
}
What does this program print?
Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int
. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b
doesn't work, that would mean a += b
would never work for bytes if it E1 += E2
was defined to be E1 = E1 + E2
. As the previous example shows, that would be indeed the case. As a hack to make +=
operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.
i+=(long)j;
even will compile fine. – Riori = (int)(i + (long)j);
– Trophoblastj
tolong
, butj
is already along
, so your casting doesn't do anything. – Fontanai += (int) f;
casts f before addition, so it's not equivalent.(int) i += f;
casts the result after assignment, not equivalent either. there would be no place to put a cast that would signify that you want to cast the value after adding, but before assignment. – Bucentauri = (int)(i + j)
. Probably the best option would be to have a compiler option to generate a warning or error... – Werbyi = j;
using the example in the question. If that were allowed without warning, you'd be throwing away half ofj
without even knowing it. The problem is compounded because implicit widening casts are allowed. So for example, consider:double x = 0.0; int y = 1; double z = 1.5; y += z; x += y;
: there are no warnings anywhere, but if you don't realizey
is anint
, you lose.5
with no warning. – Haggi