aspose file tools*
The moose likes Beginning Java and the fly likes switch case Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "switch case" Watch "switch case" New topic
Author

switch case

kedar parundekar
Ranch Hand

Joined: May 10, 2006
Posts: 40
Can any one tell me,
Why float is not usefull in switch case?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
It's not that it isn't useful. A float isn't allowed to be used as a switch variable.
kedar parundekar
Ranch Hand

Joined: May 10, 2006
Posts: 40
But why you cant use float in switch case?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
That's the specification of a switch statement.

Normally you shouldn't compare two floating point numbers for equality, because even though two numbers might look the same, because of small errors introduced by the conversion to binary or conversion of float to double, the equality test might not return true.
[ March 22, 2007: Message edited by: Keith Lynn ]
kedar parundekar
Ranch Hand

Joined: May 10, 2006
Posts: 40
But as per previous reply .....
class Demo
{
public static void main(String[] args)
{
float f1=11.2f;
float f2=11.2f;


if(f1==f2)
{
System.out.println("equal");
}
else
System.out.println("Not equal");

}
}


Above code gives me o/p- > equal?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
But try this.

pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
As has been stated above, floats lack precision. Using them in switch (if it were allowed) or in if branching statements (which is allowed) is a set up for unpredictable program behavior. Compile and run the example below to see. If your java compiler is like mine, you'll see what I mean.

[ March 22, 2007: Message edited by: pete stein ]
 
Don't get me started about those stupid light bulbs.
 
subject: switch case