Java += and implicit casting
Join the DZone community and get the full member experience.Join For Free
until today i thought that for example:
i += j;
is just a shortcut for:
i = i + j;
but what if we try this:
int i =5;long j =8;
i = i + j;will not compile but
i += j;will compile fine.
does it mean that in fact
i += j;is a shortcut for something like this
i = (type of i) (i + j)?
i've tried googling for it but couldn't find anything relevant.
as always with these questions, the jls holds the answer. in this case §15.26.2 compound assignment operators . an extract:
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.
and an example:
for example, the following code is correct:
short x =3; x +=4.6;and results in x having the value 7 because it is equivalent to:
short x =3; x =(short)(x +4.6);
in other words, your assumption is correct.
a good example of this casting is using *= or /=
byte b =10; b *=5.7;system.out.println(b);// prints 57
byte b =100; b /=2.5;system.out.println(b);// prints 40
char ch ='0'; ch *=1.1;system.out.println(ch);// prints '4'
char ch ='a'; ch *=1.5;system.out.println(ch);// prints 'a'
Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.