+ 1

Is there a difference in using a switch statement with cases and in using an if statement with else ifs (which have the same conditions as the cases)?

16th Jun 2016, 9:26 PM
Klaus
6 Answers
+ 11
yes, in case of switch case for the first time a table will be created for mapping the conditions but case of if else ladder on the excecution time only the conditions are checked. switch is faster than if else ladder
17th Jun 2016, 2:32 AM
Jarin P
Jarin P - avatar
+ 6
Yes, and for me, "if- else if" statement is BETTER than switch. For example, when comparing variables, SWITCH only allows EXACT VALUES to be compared. while in "IF - ELSE IF" statements, you may use: less than (<) greater than (>) and booleans. Scenario: you want to check a number if it is greater than 5 AND less than 12. - using "IF - ELSE IF" statements: if (num > 5 && num < 12) //print output - but using "SWITCH" statement: case 6: case 7: case 8: case 9: case 10: case 11: //print output -- And that's one of the benefits of using "IF - ELSE IF" statements compared to SWITCH statements.
19th Jun 2016, 2:37 PM
erwinmesi
erwinmesi - avatar
+ 4
it depends a lot on your use for it. if you have specific values to which you want to compare, it's far simpler and better-looking than a sequence of if-else if statements. public void function(int x){ if(x==3){ //stuff }else if(x==9){ //stuff }else if(x==27){ //stuff } } compare that to a simple switch(x){ case 3: break; case 9: break; case 27: break } now imagine that we listed up until 3^5 or 3^6, you'd have a lot of if-else statement, but one simple, cohesive, switch
20th Jun 2016, 6:53 AM
Matheus Fernandes
Matheus Fernandes - avatar
+ 2
Same as jarinp, and also the fact that switch looks much more organized and neat. Especially when you have lots of conditions.
18th Jun 2016, 9:59 PM
Raymond Feliciana
Raymond Feliciana - avatar
- 1
yes
3rd Jul 2016, 5:18 AM
Hansi Reit
Hansi Reit - avatar
- 1
yes, if you asked which better then the answer is depend on your code. if you want to check an exact value switch is better, for me switch is simpler
11th Jul 2016, 4:48 AM
Harry Marwanto
Harry Marwanto - avatar