1. Member
Join Date
Apr 2014
Posts
10
Rep Power
0

## If-Else vs Switch-Case

Hi everyone..
I'm still learning about Java, last part I've read now is looping, but before I go post about looping.. I'm still confused about if-else vs switch-case What differentiates both, where is part differentiates both? When we use if-else? when we use switch-case? I've asked for some friends, but still not get a good answer.. where i get the answer "The If-else vs switch-case is the same".

Thank you..

Regards,
R03.

2. ## Re: If-Else vs Switch-Case

A switch statement can be (and usually is) much faster than a chain of if-else if .. statements; a switch statement has 'special' code to find the matching case clause, while the chain of if-else if ... statements possibly has to test each clause in each if( ... ) part.

kind regards,

Jos

3. Member
Join Date
Apr 2014
Posts
10
Rep Power
0

## Re: If-Else vs Switch-Case

Originally Posted by JosAH
A switch statement can be (and usually is) much faster than a chain of if-else if .. statements; a switch statement has 'special' code to find the matching case clause, while the chain of if-else if ... statements possibly has to test each clause in each if( ... ) part.

kind regards,

Jos
Hi Jos,

I read too on some website were switch statement faster than if-else/if statement as like you said.. , but how to know switch statement faster than if-else/if statement ?

Below are case..

Java Code:
```public class Decision_Making_4_Switch {
public static void main (String [] args){
int x = 6;

switch (x){
case 1 :
System.out.println ("One");
break;
case 2 :
System.out.println ("Two");
break;
case 3 :
System.out.println ("Three");
break;
case 4 :
System.out.println ("Four");
break;
default :
System.out.println ("None of the above");
}
}

}
The result  : None of the above```
Java Code:
```public class Decision_Making_6 {
public static void main(String[] args) {

int x = 6;

if (x == 1) {
System.out.println("One");
} else if (x == 2) {
System.out.println("Two");
} else if (x == 3) {
System.out.println("Three");
} else if (x == 4) {
System.out.println("Four");
}

else {
System.out.println("None of above is valid");
}

}

}
The result : None of above is valid```

i'm sorry about my question :)

Regards,

R03.
Last edited by R03; 04-27-2014 at 11:22 AM. Reason: forget the result

4. Senior Member
Join Date
Feb 2014
Posts
448
Rep Power
1

## Re: If-Else vs Switch-Case

Hi,

first of all I would forget this "x is a little faster than y" stuff. That is complete nonsense regarding software development. One big rule is to keep stuff easy and simple and optimizing stuff is often simply misleading. (And if you find, that optimisation is required, then you really check where your code takes to long and then think about the possibilities. And that is NOT "I replace an if else if with a switch statement!")

And the next important things is clean code. Your code must be readable and if you have to do different things dependend on one variable, then the switch statement is much easier to read. The code is nicely structured.
But sometimes you have more complex cases e.g.
if (x == 1) {
// Do something
} else if (y == 1) {
// Do something else when x is not 1 but y is 1
} else {
// Do something when x and y are both not 1
}

But you should think about the readability and such constructs might be harder to read. There are some nice refactoring methods that could make it much easier to read:
a) introduction of methods:
if (this.isCaseA()) {
// Handle case A
} else if (this.isCaseB()) {
// handle Case B
} else {
// ...
}

But this can still be misleading because a reader might be confused because the second if is only executed when the first if check was negative.

Regarding the case statement an easy method to make it readable could be an enumeration or constants. So in code like
switch(x) {
case 1: // ...
case 2: // ...
// ...
}
You can replace the 1 / 2 / ... with readable names from a constant or enumeration.

With kind regards,

5. ## Re: If-Else vs Switch-Case

Originally Posted by kneitzel
first of all I would forget this "x is a little faster than y" stuff. That is complete nonsense regarding software development.
I (sort of) disagree w.r.t. a switch statement w.r.t. a chain of if-else-if ... statements; the applicability of a switch statement is quite small: it can compare a single integral value against a set of (unique) integral values and determine which of the case clauses is to be executed; but it does this much faster than a chain of if-else-if statements; if a switch condition applies, there is no need (imho of course) to 'mimic' it with a chain of if-else-if ... statements. Most (if not all) compilers are too stupid to do the reverse conversion (from the if-else-if statements to a switch statement) automatically.

kind regards,

Jos

6. Senior Member
Join Date
Feb 2014
Posts
219
Rep Power
1

## Re: If-Else vs Switch-Case

A factor to consider is the data type with which code branching is to be performed. The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics) has a good description on the data types that can be used in a switch statement, summarised below:
• primitives
• enumerated types
• String (from Java 7 onwards)
• special classes that wrap primitives

If code is to be branched based on arbitrary and/or complex logical conditions, then you'd find that it'll be very awkward to use switch-case. E.g., I wouldn't use switch-case if branching is dependent on:
• if a File object is associated with a file (as opposed to a directory), and
• the file's length is < 5000 bytes, or
• if the File object is associated with a directory

Doing the above using if-else would be something like
Java Code:
`if ((file.isFile() && file.length() < 5000) || file.isDirectory())`
I wouldn't implement this using switch-case.

Another factor to consider is the features that are made available for use. E.g., switch-case supports "fall through." The SwitchDemoFallThrough example from the tutorial link above shows how this feature can be exploited to produce quite-neat code compared to an implementation using if-else (which I'd leave as an exercise for you).

In general, imo, you choose the one that results in simpler and more readable code.

7. Senior Member
Join Date
Feb 2014
Posts
448
Rep Power
1

## Re: If-Else vs Switch-Case

Jos: First of all I want to point out that I am also saying, that a switch statement should be used when possible.

But the argument regarding speed could be misleading. If speed starts to be an argument, then people could use this as an argument against other rules that help with clean code. So instead of introducing small functions you start having bigger functions and maybe even double code because a function call comes with an overhead... arguments like that.

And maybe a chain of if else if is optimized in the future. Maybe they find a way that it is even faster than your switch statement. Do you start rewriting your code? (If that is an real argument you might want to)...

In my eyes a switch statement is much easier to read and that is the main reason why I am using that wherever possible.

And that is the same reason why I use which loop. Instead of while (condition) you could write for (;condition;) { } and even add some commands at the initializing step and the increment step ... But the different loops are used in different areas and developers are used to that usage. So for clean code you should stick to that usage.

I hope I was able to clarify my position. Of course: I do not want to convince anyone. It is completely ok (and normal) that developers have a different view what "clean code" means and which areas are how important.

8. Just a guy
Join Date
Jun 2013
Location
Netherlands
Posts
3,693
Rep Power
5

## Re: If-Else vs Switch-Case

Originally Posted by kneitzel
In my eyes a switch statement is much easier to read and that is the main reason why I am using that wherever possible.
Fall-through and labels.

That's why I detest the switch statement and will forever and always avoid it. But I won't recommend other people to do the same, its a personal thing. Enforcing your own opinion on others is not the way to go, people should use what they're comfortable with.

9. Senior Member
Join Date
Feb 2014
Posts
448
Rep Power
1

## Re: If-Else vs Switch-Case

Originally Posted by gimbal2
Fall-through and labels.
That are good points / arguments! And exchange of arguments is never bad. But it always depends on the persons what they do out of it (e.g. static code checks that gives a warning or error when a break is missing. Or simply be more aware about the risk.)

With kind regards,

10. Member
Join Date
Apr 2014
Posts
10
Rep Power
0

## Re: If-Else vs Switch-Case

Originally Posted by JosAH
I (sort of) disagree w.r.t. a switch statement w.r.t. a chain of if-else-if ... statements; the applicability of a switch statement is quite small: it can compare a single integral value against a set of (unique) integral values and determine which of the case clauses is to be executed; but it does this much faster than a chain of if-else-if statements; if a switch condition applies, there is no need (imho of course) to 'mimic' it with a chain of if-else-if ... statements. Most (if not all) compilers are too stupid to do the reverse conversion (from the if-else-if statements to a switch statement) automatically.

kind regards,

Jos
Hi Jos,

where can compare single integral against a set of (unique) integral values

many thanks

Regards,
R03.

Originally Posted by jashburn
A factor to consider is the data type with which code branching is to be performed. The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics) has a good description on the data types that can be used in a switch statement, summarised below:
• primitives
• enumerated types
• String (from Java 7 onwards)
• special classes that wrap primitives

If code is to be branched based on arbitrary and/or complex logical conditions, then you'd find that it'll be very awkward to use switch-case. E.g., I wouldn't use switch-case if branching is dependent on:
• if a File object is associated with a file (as opposed to a directory), and
• the file's length is < 5000 bytes, or
• if the File object is associated with a directory

Doing the above using if-else would be something like
Java Code:
`if ((file.isFile() && file.length() < 5000) || file.isDirectory())`
I wouldn't implement this using switch-case.

Another factor to consider is the features that are made available for use. E.g., switch-case supports "fall through." The SwitchDemoFallThrough example from the tutorial link above shows how this feature can be exploited to produce quite-neat code compared to an implementation using if-else (which I'd leave as an exercise for you).

In general, imo, you choose the one that results in simpler and more readable code.
Hi jashburn,

thank you for simple explaining.. actually i'm not yet learning like that.. still do simple programming, from the source you have shared, i have a lot of question before i answer your question about (exercise) you asked..

i apologize.. because i learn very slowly...

for my exercise could make another simple question ?

regards,
R03.

Thank you very much for explaining, still reading and learning from your comment..

regards,
R03.
Last edited by R03; 04-29-2014 at 02:05 AM.