Switch Statement
Switch statement is useful because it is used to match constant values. Switches use a key word called Case. Cases are used to specify the constant to match. There is a special case called Default. The default case only gets hit when all other cases fail, and it located as the last case.
Be aware that not all variables can be used. Mostly all built in types will work, like int, char, byte, boolean etc. Strings can also be used but they are implemented using a hidden dictionary which is different to the other types.
The basic switch syntax is as follows:
switch(value)
{
case Case Value 1:
// Case value 1 code goes here
break;
case Case Value 2:
// Case value 2 code goes here
break;
default:
// default code goes here if all other cases fail
break;
}
Each case code has “break; “, this is required. If it was not there, then the code would run into the next case. The code will still compile fine without it. The break merely breaks out from the switch.
Notice the default case, this case gets run if all other cases fail, you don’t have to put “break;” here but it is good practice and keeps consistency if you do. Default is not required for the switch to work, but if it is not there, when all other cases fail the code will leave the switch and continue to run the rest of the code.