Wednesday 15 May 2019

java - Why does the narrowing conversion from int to short not work if local variable is used in the ternary operator



The following line of code is accepted by the compiler (sun-jdk-8u51) without any warnings or errors:



short b = true ? 1 : 1;



Whereas the next two code lines lead to a compilation error (incompatible types: possible lossy conversion from int to short):



boolean bool = true;
short s = bool ? 1 : 1;


Why is the compiler not able to perform the same narrowing conversion of the primitive integer 1 in the second case?


Answer




As outlined by @aioobe in the comments:




This is because in the first case, since true is a compile time constant, the whole expression is evaluated during compile time, so you basically have short b = 1; whereas in the second version, the compiler does not do the simplification for you, hence the error




Adding final to the declaration of the variable bool makes it a constant variable, which also allows the compiler to interpret the code as mentioned above.



final boolean bool = true;
short s = bool ? 1 : 1;



See section 4.12.4


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