It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Float.POSITIVE_INFINITY...? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Float.POSITIVE_INFINITY...?" Watch "Float.POSITIVE_INFINITY...?" New topic


Prashant Neginahal
Ranch Hand

Joined: Dec 04, 2002
Posts: 76
Hi All,
int j = (int)Float.POSITIVE_INFINITY;
j==Integer.MAX_VALUE; It gives true
short i = (short)Float.POSITIVE_INFINITY;
i == Short.MAX_VALUE;It gives false
I really not understanding these two cases, will anyone please explian me.?

--------------<br />Prashant<br />SCJP-91%
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Beware of casts to integer types other than long or int. They do not work the way you might think.
When you convert a float (or double) to a byte, short, or char, the number is first converted to an int and then truncated to a short.
So what happens in this case is that Float.POSITIVE_INFINITY is converted to Integer.MAX_VALUE (01111111111111111111111111111111), then this value is simply truncated to a 16 bit short value (1111111111111111). The result is therefore -1 rather than Short.MAX_VALUE (0111111111111111).
The details are in the JLS section 5.1.3 Narrowing Primitive Conversions.
- Peter
I agree. Here's the link:
subject: Float.POSITIVE_INFINITY...?
It's not a secret anymore!