More Examples of the switch Statement
In this lesson, we will look at examples of the switch statement with a character or an enumerated data type.
We'll cover the following...
Character values with a switch
statement
The action of a switch
statement can be based upon a character. For example, if the char
variable grade
contains a letter grade, the following switch
statement assigns the correct number of quality points to the double
variable qualityPoints
:
public class Example{public static void main(String args[]){double qualityPoints;// Assume that the variable grade contains a character that ranges from 'A' to 'F'char grade = 'D';switch (grade){case 'A':qualityPoints = 4.0;break;case 'B':qualityPoints = 3.0;break;case 'C':qualityPoints = 2.0;break;case 'D':qualityPoints = 1.0;break;case 'F':qualityPoints = 0.0;break;default:System.out.println("grade has an illegal value: " + grade);qualityPoints = -9.0;System.exit(0);} // End switchSystem.out.println("The grade " + grade + " represents " + qualityPoints + " quality points.");} // End main} // End Example
📝 Note: Why does the default case assign a value to
qualityPoints
?Without this assignment in the previous
switch
statement, or if we choose to omit the default case altogether, the compiler will think it possible forqualityPoints
to remain uninitialized after theswitch
statement. We will get a syntax error. Another way to avoid the syntax error is to initializequalityPoints
to a value before theswitch
statement. ...