• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting Difference of Float.POSITIVE_INFINITY

 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jimmy Thomas
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Alexey Korneychuk
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think
{byte b = (byte) f;} the same { byte b = (byte) (int)f;}

But not sure
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Arun kumar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Swathi Sree
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Test1 {

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

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

This would answer your question
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic