Why are op-assign statements not safe in Java?

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

I found out that it will not work in Java:

int a = ...;
a = 5.0;

but it will be:

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

Ie, it seems that the = operator is type safe, but + = not. Is there any serious reason for this or is it just another arbitrary decision maker who needs to make a decision.

+3
source share
2 answers

Make life easier.

Release a little further. Consider:

byte b;
...
++b;

The increment really does:

b = (byte)(1 + (int)b);

Even using +=, it does not get better:

b += b;

is an:

b = (byte)((int)b+(int)b);

This would make these statements useless for / short / char bytes.

, , .

+1

, :

a += 5.0; :

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

, , .

( float, double, , Java .)

+5

Source: https://habr.com/ru/post/1703895/


All Articles