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 Is switchcase is better than if else Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Is switchcase is better than if else" Watch "Is switchcase is better than if else" New topic

Is switchcase is better than if else

Ali Asghar

Joined: Sep 19, 2001
Posts: 1
Is switch case is better than if else and why?
Chris Shepherd
Ranch Hand

Joined: Jun 27, 2000
Posts: 286
Depends on what you need it for. switch is better for picking between lots of options but I think all options have to be numeric. if is boolean based, and can be nested inside other if statements, but if you have lots of options, it can get ugly. I'm not sure about the internal workings of java with these two. With if I know you have to go through every boolean check above the correct option before you get to the correct one. I suspect that switch works in such a way as to minimize the "select the correct option" branch.
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
I've actually read a couple of books that avoid switch all together. Since I don't have them in front of me, I can't site exactly why they do, but I think it has something to do with switch not really exhibiting OO-type behavior (kind of like goto). Anyway, I personally don't use it unless it is specifically asked for, I find using if/else statements easier in both usage and reading.
I agree. Here's the link:
subject: Is switchcase is better than if else
It's not a secret anymore!