Tuesday 4 December 2018

java - "+=" operator and int long usage





int a = 1L;


This doesn't compile (of course).
incompatible types: possible lossy conversion from long to int



int b = 0;
b += Long.MAX_VALUE;



This does compile!



But why is it allowed?


Answer



When you do += that's a compound statement and Compiler internally casts it. Where as in first case the compiler straight way shouted at you since it is a direct statement :)



The line



b += Long.MAX_VALUE;



Compiler version of it equivalent of



b += (int)Long.MAX_VALUE;


of course there will be lossy conversion from conversion of long to int.



http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#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.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...