switch and if both seem very similar to me and I’m not sure i understand why you might choose one over the other.
I think of “switch” as being a specialised and limited form of “If” .
So say you were trying to do something based on the color of something.
if(color == red) {
// do A
}
else if(color == green) {
// do B
}
This could be written using switch :
switch(color){
case red: //do A
break;
case green: //do B:
break;
}
So for this limited type of use where u are matching a single value either of the 2 would work and infact switch would be a bit more easier to read arguably.
But now say you want to do something based on more than 1 value…
say you want to do something when color = red but style != Jacket for either user Uma or Unni
This would not be possible using a switch. But using if you could write :
if(color == red
&& style != "Jacket"
&& (user == "Uma" || user == "Unni") ){
// do something
}
So basically if / else if allows you combine multiple set of logical conditions to be met per if statement.
Hope this helps.
Here’s a nice article that describes son pros and cons:
There’s no real difference other than clarity and speed, switch might be faster in some cases but that’s it. I also read that using switch is considered bad practice, Why? Well, here’s a nice discussion that sheds some light to the topic:
As you can read, the only reason it is considered bad practice is because people tend to overuse the statement, try not to use it as often, BUT if you are a beginner and Switch is one of your primary tools, go ahead and overuse it, just be sure to keep learning so you can find other, more elegant and clean answers.
To add a little extra to this topic: I haven’t used Switch in years, I’m not even joking, years without using that statement, that’s because I now organize my code better and use other things you’ll eventually learn like abstract classes, interfaces, hash tables andmore. I’m not saying the course is teaching bad stuff, I’m just saying the more experience you’ll get the less you’ll use certain things, but I insist, for beginners a Switch statement is great.
Beautiful explanation
This really helped me understand the difference, I know he said single values before but it just didn’t click until you showed how you can punch in more variables like must be a red jacket used by either Uma or Unni