The Switch Statement

Previously, I covered several ways to handle multiple situations based on the input received in code via the if, else, and else if statements. However, for covering multiple situations with a more precise range (such as only one number or letter) a more compact method is the Switch Statement. At the start of the switch statement, the input to use is given. From that point, each case is given with how the code would react. For instance, let's say that I have an integer variable of x that can only possibly hold numbers between 1 to 5 and from this we determine a student's grade. From this, we can come up with how the program will handle each number as seen in the following code:

String grade;
switch (x){
case 1:
      grade = "A";
case 2:
     grade = "B";
case 3:
     grade = "C";
case 4:
     grade = "D";
case 5:
     grade = "F";

Now, there are a few things to point out. After a case is matched, to make sure that the next case isn't executed, the break keyword is used to exit the switch statement. Also, to cover the scope of the switch statement, curly brackets or braces (which actually have several names) are utilized to indicate the start and end of the scope. Just remember that this is a solution when each precise match is to be handled differently. For handling ranges and enumerations, using else if is more effective.