Java Magazine, Nov/Dec 2017
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2017 96 fix this Notice also that adding a cast to the literal wont work An integer expression can be cast to a long expression although its not necessary to do so but that doesnt afect the type of the literal that forms the expression So line 14 fails to compile Line 15 attempts to declare and initialize three short values The range of a short in Java is 32768 to 32767 that is the range of a 16 bit twos complement binary number Therefore its certainly possible to fit 100 99 and even 199 into the short In fact the first two assignments work successfully the compiler works out that the literal expressions 100 and 99 which you saw above are of int type will fit without loss of precision into the variables s1 and s2 However the assignment of s3 does not work The problem here is that the compiler sees an expression involving two short values and the plus operator All arithmetic is performed The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method using at least int sized values and therefore the result of the add operation is an intsized value not a short value At that point the compiler complains because it cannot safely take an unknown int value and assign it to a short unless you cast that value Of course the cast isnt safe but youd be accepting responsibility for any problems Because of this line 15 also fails to compile One way to make line 15 compile would be to add a cast 15 short s1 99 s2 100 s3 short s1 s2 Interestingly however you could change the code so that the declarations of s1 and s2 are final If you do that the compiler recognizes that the value of the expression being assigned to s3 must be 199 s1 s2 becomes a constant expression at compile time and the compiler is once again willing to perform the assignment without complaint Line 16 might look simple enough but it too fails to compile The reason is that the literal value 314 is a double expression and attempting to assign this to a float value will fail The
You must have JavaScript enabled to view digital editions.