Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

switch case

 
kedar parundekar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one tell me,
Why float is not usefull in switch case?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not that it isn't useful. A float isn't allowed to be used as a switch variable.
 
kedar parundekar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But why you cant use float in switch case?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But try this.

 
pete stein
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic