Switching to make decisions
We have seen the vast and virtually limitless possibilities of combining the Java operators with if
and else
statements. But sometimes, a decision in Java can be made better in other ways.
When we must decide based on a clear list of possibilities that don't involve complex combinations, then switch is usually the way to go.
We start a switch
decision like this:
switch(argument){ }
In the previous example, an argument could be an expression or a variable. Within the curly braces, {}
, we can make decisions based on the argument with the case
and break
elements:
case x:      // code to for case x      break; case y:      // code for case y      break;
In the previous example, you can see that each case
states a possible result and that each break
denotes the end of that case, as well as the point at which no further case statements will...