The switch Statement


The switch Statement

In the last chapter, you coded methods in HonorsGradingStrategy and RegularGradingStrategy to return the proper GPA for a given letter grade. To do so, you used a succession of if statements. As a reminder, here is what some of the relevant code looks like (taken from HonorsGradingStrategy):

 int basicGradePointsFor(Student.Grade grade) {    if (grade == Student.Grade.A) return 4;    if (grade == Student.Grade.B) return 3;    if (grade == Student.Grade.C) return 2;    if (grade == Student.Grade.D) return 1;    return 0; } 

Each of the conditionals in basicGradePointsFor compares a value to a single variable, grade. Another construct in Java that allows you to represent related comparisons is the switch statement:

 int basicGradePointsFor(Student.Grade grade) {    switch (grade) {       case A: return 4;       case B: return 3;       case C: return 2;       case D: return 1;       default: return 0;    } } 

As the target of the switch statement, you specify a variable or expression to compare against. In this example, the target is the grade parameter:

 switch (grade) { 

You then specify any number of case labels. Each case label specifies a single enum value. When the Java VM executes the switch statement, it determines the value of the target expression. It compares this value to each case label in turn.

If the target value matches a case label, the Java VM transfers control to the statement immediately following that case label. It skips statements between the switch target and the case label. If the target value matches no case label, the Java VM transfers control to the default case label, if one exists. The default case label is optional. If no default case label exists, the VM transfers control to the statement immediately following the switch statement.

Thus, if the value of the grade variable is Student.Grade.B, Java transfers control to the line that reads:

 case B: return 3; 

The Java VM executes this return statement, which immediately transfers control out of the method.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net