Search⌘ K
AI Features

More Examples of the switch Statement

Explore various examples of the Java switch statement including handling character values, enumerated types, and omitting break statements. Understand when to use switch statements versus if statements for clearer and more efficient multiway decision-making in your Java programs.

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:

Java
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. ... ...