why byte += 1 compile but byte = byte + 1 not?
If I have a byte variable: byte b = 0;
why does the following work:
b++;
b += 1; // compiles
... but this does not ?
b = b + 1; // compile error
Does compiler understand first as byte
and second as int
?
[EDIT]
I know casting but I want to draw your attention to the b++, b += 1 and b = b + 1
I think they are equal so why compiler differs them ? what is the difference between
b += 1 and b = b + 1 ?
Solution 1:
Because b += 1
is an equivalent to b = (byte)(b + 1)
, whereas type of b + 1
is promoted to int
(JLS §5.6.2 Binary Numeric Promotion) and therefore its result cannot be assigned to byte
without explicit conversion.
From JLS, §15.26.2 Compound Assignment Operators:
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.
Solution 2:
Possible loss of precision is the problem. Cast it and it is OK.
b = (byte) (b + 1);
Solution 3:
Yes, the result of the +
-operation is int
, so a cast is needed in order to assign it to a byte
variable.
Solution 4:
In java the default for integers is int, and for floating point numbers it is double. So b
is by default converted to integer to perform the operation. So the resultant answer needs to be typecasted before being stored to prevent any possible loss of precision. But b+=1
does it automatically.