Why does the Java increment operator allow narrowing operations without explicit cast? [duplicate]

若如初见. 提交于 2020-01-01 07:28:08

问题


Possible Duplicate:
Java += operator

In Java, this is not valid (doesn't compile), as expected:

long lng = 0xffffffffffffL;
int i;
i = 5 + lng;    //"error: possible loss of magnitude"

But this is perfectly fine (?!)

long lng = 0xffffffffffffL;
int i = 5;
i += lng;       //compiles just fine

This is obviously a narrowing operation, that can possibly exceed the int range. So why doesn't the compiler complain?


回答1:


i += lng; compound assignment operator cast's implicitly.

i+=lng; 
is same as 
i = int(i+lng);

FROM JLS:

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.




回答2:


This is defined in the JLS #15.26.2:

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.

In other words, i += lng performs a cast implicitly.




回答3:


The compiler does not complain because, according to JLS §15.26.2. Compound Assignment Operators:

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.

Thus,

i += lng;

is equivalent to

i = (int)(i + lng);


来源:https://stackoverflow.com/questions/13949840/why-does-the-java-increment-operator-allow-narrowing-operations-without-explicit

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