Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch Statement

 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to have a switch statement in which the cases define a range?

switch(available){

case < 100:
// do this
break;

case >=100:
// do this
break;

}

Thanks!

Drew
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. Best you could do is this:

Not very good. Better use an if statement.
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul is correct.
No is the answer.

The switch statement came from C.

There is was used as an optimization. There are certain kinds of comparisons that the compiler can optimize. Exact comparisons of simple values. They are much easier to identify and optimize when they are using a different syntax.

The optimization could not take place if it was a range, so there was no reason to add that.

My personal opinion is that you should almost always use if rather than switch.
 
camilo lopes
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not you can't do this.
the case of switch can't have condition for test.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic