+ 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?
3 Respuestas
+ 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
+ 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
0
yeah