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

switch case v/s if else

 
Chinmay Bajikar
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In cases where there is a long chain of if-else if 's is it better to have it replaced by swich case statements.
and also in normal cases, which one of the two is better in terms of performance and memory usage.
not to mind the readablity and understanding parameter.
Thanks,
Chinmay.
 
Ken Manohar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the comparison for the if statement involves an int or a char variable ,e.g. if(num == 10), ONLY then a switch statement can be subsituted for the if statement.
Generally, a switch statement is more efficient than a corresponding if statement. However, you must cater for "fall through" in a switch statement, and you should always include a 'default' case.
 
Sal Velinus
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I come more from C++, still learning Java, but I rarely see switch statements used. Menus use them. It's not that they're never used, but if you have a large number of cases (or if/elses), you might want to rethink your design, see if you could simplify it. Sometimes arrays are useful here, especially if you're performing the same operation on each case, i.e. updating counters, etc.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic