Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't op-assign operators type safe in java?

I'm not sure the question is clearly worded, but an example will be clearer.

I found out that will not work in Java:

int a = ...;
a = 5.0;

but this will:

int a = ...;
a += 5.0;

I.e., it seems that the = operator is type safe but += isn't. Is there any deep reason for this or is it just another arbitrary decision language designers must take.

like image 896
flybywire Avatar asked Dec 06 '25 06:12

flybywire


1 Answers

The reason is that math operations do some implicit casting:

a += 5.0; is evaluated as follows:

a = (int) ((double) a + 5.0);

Assignment, however, requires an explicit cast.

(It might be float rather than double, I don't remember which Java treats as decimal literals.)

like image 82
Powerlord Avatar answered Dec 07 '25 22:12

Powerlord



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!