Saturday 20 January 2018

java - Adding int to short





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?


itemprop="text">
class="normal">Answer




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.



- href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2"
rel="noreferrer">JLS
§15.26.2




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...