...

/

More Examples of the switch Statement

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.

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:

Press + to interact
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 switch
System.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 for qualityPoints to remain uninitialized after the switch statement. We will get a syntax error. Another way to avoid the syntax error is to initialize qualityPoints to a value before the switch statement. ...

Access this course and 1400+ top-rated courses and projects.