+ 3

Java: switch VS if -- else if statements

Hello there! For example, I have int x with 10 possible values (1--10). And what happens in program next depends from this value. So what should I use? switch with 10 (+def) cases, or a bunch of if--else if? What is better and works faster (and for what data type)? Facts and opinions both welcome! P.S. I've heard that programmers try to avoid using switch (idk why), what do you think about it?

13th Mar 2017, 3:57 AM
Gleb Yeremeyev
Gleb Yeremeyev - avatar
3 Réponses
+ 3
Switch case is much faster than if else, as in if else,. compiler checks for each if else and proceeds if its false.In switch , it deirectly passes to rrquired case. switch case is probably more readable. if else, is better as we can use if(x=0 && x=9) etc, In switch case that is not possible
13th Mar 2017, 5:19 AM
Meharban Singh
Meharban Singh - avatar
+ 1
switch statement is better in the situations where single expression has to be evaluated against multiple fixed values. On the other hand, if..else is a better option while evaluating non equalities
13th Mar 2017, 5:57 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
0
yeah
4th Apr 2017, 2:53 PM
sadffads