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
1 Respuesta
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