Can someone explain why changing the short to a long means that d will now be > 0?
Daniel Whyte
Level 17
(Short) to (long)
Under discussion
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
11 March 2021, 15:04useful
That line has a double (variable f) that is divided by 0 (variable c). When this occurs it results in the double becoming infinity. When casting from infinity to a narrower number type (double is the widest primitive so casting to anything else would be narrowing) there are special rules. Besides float which can and would also be infinity, the rules state that Infinity becomes either Long.MAX_VALUE if cast to a long, or Integer.MAX_VALUE if cast to anything else. Both of these have the binary representation of a 0 followed by all 1's.
(Just FYI: Negative infinity would become long or int MIN_VALUE instead)
Now casting to a short, byte, or char would first result in casting to the max value of int and then to the smaller type. When casting down from a wider type the rules state that the extra bits are just dropped off, so you end up with the binary of all 1's. This is going to equal -1.
So:
Long.MAX_VALUE = 0111111111111111111111111111111111111111111111111111111111111111
Integer.MAX_VALUE = 01111111111111111111111111111111
-1 in short = 1111111111111111
Short.MAX_VALUE = 0111111111111111
Here are conversion rules from the Oracle docs:
Java Docs
Skip to "5.1.3. Narrowing Primitive Conversion"
+1