• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is switchcase is better than if else

 
Ali Asghar
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is switch case is better than if else and why?
 
Chris Shepherd
Ranch Hand
Posts: 286
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1932
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Jason
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic