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 case v/s 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 "switch case v/s if else" Watch "switch case v/s if else" New topic

switch case v/s if else

Chinmay Bajikar
Ranch Hand

Joined: Dec 08, 2001
Posts: 159
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.

The strength of the Wolf is the pack & the strength of the pack is the wolf....Rudyard Kipling
Ken Manohar

Joined: Mar 16, 2002
Posts: 4
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

Joined: Mar 05, 2002
Posts: 25
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.
I agree. Here's the link:
subject: switch case v/s if else
It's not a secret anymore!