Alex Rivera | Logout

When to use If-else if-else over switch statements and vice versa

Asked 2009-01-09T11:33:54.297
118

Why you would want to use a switch block over a series of if statements?

switch statements seem to do the same thing but take longer to type.

Edit
Report

2 Answers

64

If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.

Otherwise, stick with multiple if-else statements.

answered 2009-01-09T11:37:32.603
0

This depends very much on the specific case. Preferably, I think one should use the switch over the if-else if there are many nested if-elses.

The question is how much is many?

Yesterday I was asking myself the same question:

public enum ProgramType {
    NEW, OLD
}

if (progType == OLD) {
    // ...
} else if (progType == NEW) {
    // ...
}

if (progType == OLD) {
    // ...
} else {
    // ...
}

switch (progType) {
case OLD:
    // ...
    break;
case NEW:
    // ...
    break;
default:
    break;
}

In this case, the 1st if has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.

I ended up choosing the switch because it just reads better.

answered 2009-01-09T12:13:13.807

Your Answer