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

核能气质少年 提交于 2019-12-01 09:14:23

To make life easier.

Let's go a little further. Consider:

byte b;
...
++b;

The increment is really doing:

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

Even using += it doesn't get any better:

b += b;

is:

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

That would make these operators useless for byte/short/char.

Of course I wont be happy until we have arbitrary sized integers.

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.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!