| Author |
Casting Difference of Float.POSITIVE_INFINITY
|
Sandeep Chhabra
Ranch Hand
Joined: Aug 28, 2005
Posts: 340
|
|
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
|
Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
|
 |
Jimmy Thomas
Greenhorn
Joined: Aug 17, 2005
Posts: 19
|
|
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
Joined: Sep 06, 2005
Posts: 18
|
|
I think {byte b = (byte) f;} the same { byte b = (byte) (int)f;} But not sure
|
 |
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
|
|
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.
|
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
|
 |
Arun kumar
Greenhorn
Joined: Sep 17, 2005
Posts: 19
|
|
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
Joined: Aug 27, 2005
Posts: 19
|
|
class Test1 { public static void main(String[] args) { System.out.println(Float.POSITIVE_INFINITY == Double.POSITIVE_INFINITY); } } --------Output-------- true ---------------------- This would answer your question
|
 |
 |
|
|
subject: Casting Difference of Float.POSITIVE_INFINITY
|
|
|