A colleague of mine asked this question to me and I am kind of confused.
int i = 123456;
short x = 12;
The statement
x += i;
Compiles fine however
x = x + i;
doesn't
What is Java doing here?
Type promotion allows you to look at certain types, and determine which type is wider. It then creates a temporary value of the wider type to the operand with the narrower type. Thus, if you add a short to an int, short is the narrower type, so a temporary int with the closest value to the short is created.
The java. lang. Short. intValue() method returns the value of this Short as an int.
short datatype is the variable range is more than byte but less than int and it also requires more memory than byte but less memory in comparison to int. The compiler automatically promotes the short variables to type int, if they are used in an expression and the value exceeds their range.
int i = 123456;
short x = 12;
x += i;
is actually
int i = 123456;
short x = 12;
x = (short)(x + i);
Whereas x = x + i
is simply x = x + i
. It does not automatically cast as a short
and hence causes the error (x + i
is of type int
).
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.- JLS §15.26.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With