Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 878
Cristian Diaconescu Avatar asked Dec 19 '12 10:12

Cristian Diaconescu


2 Answers

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.

like image 151
assylias Avatar answered Oct 22 '22 17:10

assylias


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.

like image 36
PermGenError Avatar answered Oct 22 '22 19:10

PermGenError