Win a copy of Rust Web Development this week in the Other Languages forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Tim Cooke
• Campbell Ritchie
• Ron McLeod
• Liutauras Vilda
• Jeanne Boyarsky
Sheriffs:
• Junilu Lacar
• Rob Spoor
• Paul Clapham
Saloon Keepers:
• Tim Holloway
• Tim Moores
• Jesse Silverman
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Piet Souris
• Frits Walraven

# Casting Difference of Float.POSITIVE_INFINITY

Ranch Hand
Posts: 340
• Number of slices to send:
Optional 'thank-you' note:
Hi,
Consider the following Code:

This code compiles fine and gives the output :
----------------------------------------------
-1
2147483647
----------------------------------------------

Can anyone explain why there is difference between the result of two casting?

Thanx

Sandy

Greenhorn
Posts: 19
• Number of slices to send:
Optional 'thank-you' note:
Sandy,

Try this

Output:
----------------------------------
-1
2147483647
-1
1111111111111111111111111111111
11111111111111111111111111111111
2147483647

I guess this should explain... narrow conversion.
[ September 16, 2005: Message edited by: Jimmy Thomas ]

Greenhorn
Posts: 18
• Number of slices to send:
Optional 'thank-you' note:
I think
{byte b = (byte) f;} the same { byte b = (byte) (int)f;}

But not sure

Ranch Hand
Posts: 7729
• Number of slices to send:
Optional 'thank-you' note:
You would have expected that the byte cast would result in +127 (the maximum possible positive byte value). Horror!

I also suspect it's because casting to byte is done via a cast to int. That is Float.POSITIVE_INFINITY gets first cast to Integer.MAX_VALUE. Then the cast to byte just takes the least 8 bits of Integer.MAX_VALUE to get -1.

Greenhorn
Posts: 19
• Number of slices to send:
Optional 'thank-you' note:
public class Test
{
public static void main(String[] a)
{
float f = Float.POSITIVE_INFINITY;
byte b = (byte)f;
int i = (int)f;
short s = (short)f;
System.out.println(b);
System.out.println(s);
System.out.println(i);
System.out.println(f);

double d = Double.POSITIVE_INFINITY;
long l = (long)d;
int j = (int)d;
System.out.println(l);
System.out.println(j);

}
}
------------------ output ------------------
-1
-1
2147483647
Infinity
9223372036854775807
2147483647
---------------------------------------------

i was expecting -2147483648 for the last SOP. anyone please explain.

Greenhorn
Posts: 19
• Number of slices to send:
Optional 'thank-you' note:
class Test1 {

public static void main(String[] args) {
System.out.println(Float.POSITIVE_INFINITY == Double.POSITIVE_INFINITY);
}
}

--------Output--------
true
----------------------