File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Switch Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Switch Statement" Watch "Switch Statement" New topic

Switch Statement

Drew Lane
Ranch Hand

Joined: May 13, 2001
Posts: 296
Is it possible to have a switch statement in which the cases define a range?


case < 100:
// do this

case >=100:
// do this



Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

No. Best you could do is this:

Not very good. Better use an if statement.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
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.

Bill Shirley - bshirley -
if (Posts < 30) JavaRanchFAQ);
camilo lopes
Ranch Hand

Joined: Aug 08, 2007
Posts: 202
Not you can't do this.
the case of switch can't have condition for test.

Brazil - Sun Certified Java Programmer - SCJP 5 About Java - Update every Week.
Guide SCJP - tips that you need know
I agree. Here's the link:
subject: Switch Statement
jQuery in Action, 3rd edition