Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding int to short [duplicate]

Tags:

java

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?

like image 911
Em Ae Avatar asked Sep 21 '12 20:09

Em Ae


People also ask

Can we add int and short?

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.

Can we assign short to int in Java?

The java. lang. Short. intValue() method returns the value of this Short as an int.

Can a short be 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.


1 Answers

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 to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

- JLS §15.26.2

like image 95
arshajii Avatar answered Oct 13 '22 01:10

arshajii