Java Switch | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Java Switch

Can someone give me an example of where a Switch case would be used? In an application maybe? It seems more difficult than useful

3rd Jul 2018, 8:32 PM
F K
F K - avatar
1 Answer
0
Basically you use switches everywhere you would use a long list of if/else ifs that all check the same variable. for example if (type == 1) { // do stuff } else if (type == 2) { // do stuff } else if (type == 3) { // do stuff } else { // do other stuff } can be rewritten to switch (type) { case 1: // do stuff break; case 2: // do stuff break; case 3: // do stuff break; defaut: // do other stuff } which is easier to read. A common use case in Java are enums: public enum Day { MONDAY, TUESDAY, WEDNESDAY, ... } then you can switch (myDay) { case MONDAY: // ... case TUESDAY: // ... ... } Don't forget about the break statements though. :D
3rd Jul 2018, 8:51 PM
Schindlabua
Schindlabua - avatar