When do i use switch? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

When do i use switch?

i don't get it really, over what kind of situation do i need to apply it?

20th Apr 2018, 11:09 PM
Buster
Buster - avatar
4 Answers
+ 7
I usually wait until I've got more than 3 choices of my variable. if (x == 0) ;//do something else if (x == 1) ;//do something else if (x == 2) ;//do something else ;//do something I'd use a switch for this. It use to be that using a switch ended up generating better code than the if code would get. However, the odds are good that today's compilers will automatically switch your if or switch to use which ever has the better code so it doesn't matter.
21st Apr 2018, 12:42 AM
John Wells
John Wells - avatar
+ 3
@John Wells This person is asking in java... And despite that you answered a ‘else if’ clause.
21st Apr 2018, 4:32 AM
syul
syul - avatar
+ 1
syul what I coded compiles and runs in Java.
21st Apr 2018, 2:15 PM
John Wells
John Wells - avatar
+ 1
i actually get it now, it's basically the same function as an if
21st Apr 2018, 2:43 PM
Buster
Buster - avatar