Java Magazine, May/June 2019
ORACLE COM JAVAMAGAZINE MAY JUNE 2019 84 fix this not evident or even possible here because the float to long assignment and actually assignment of any Java floating point primitive type to any Java integer primitive type is always rejected due to loss of range youll see later that Java permits assignments that might simply lose some precision Option C assigns a char value to an int Every value that can be represented by a char can be represented perfectly by an int Therefore the result is reliably accurate the compiler permits it and option C is correct Option D assigns a long to a float The range of a float is much greater than the range of a long and the compiler allows this Therefore option D is also correct It might seem odd that a long has 8 bytes of efective storage and a float has only 4 bytes That might seem like option D should be rejected But again the issue here relates to loss of precision not loss of gross value This will be investigated further in a moment Option E attempts to assign a float to an int but as the table shows the range of a float is vastly greater than that of an int and therefore the attempt is rejected by the compiler and option E is incorrect At this point youve seen that assignments that might result in a completely wrong value based on the ranges representable by the types will be rejected by the compiler but you can force the compilers hand by using a cast A cast operation is safe if youre sure the value will fit Youve also seen that an assignment that risks losing only precision not gross value is permitted The rules described in Java Language Specification sections 512 and 513 are concerned with whats permitted and what might happen not with understanding the consequences At this point youve not seen how an assignment could cause the issue raised here So now lets look closer at it and as a side thought consider how a 4 byte float value can store a larger range than an 8 byte long value Its easy to understand losing the fractional part when you assign through a cast a float to an int but what does it mean to lose precision when you assign for example a long to a float The answer lies in how the float manages to have a wider range than the long despite using half the storage
You must have JavaScript enabled to view digital editions.