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.
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:
📝 Note: Why does the default case assign a value to
qualityPoints?Without this assignment in the previous
switchstatement, or if we choose to omit the default case altogether, the compiler will think it possible forqualityPointsto remain uninitialized after theswitchstatement. We will get a syntax error. Another way to avoid the syntax error is to initializequalityPointsto a value before theswitchstatement. ... ...