Java Reference
In-Depth Information
Display 3.2
A switch Stat ement (part 2 of 2)
Sample Dialogue 3
Enter number of ice cream flavors:
3
3 flavors
is acceptable.
Sample Dialogue 4
Enter number of ice cream flavors:
9
I didn't plan for
9 flavors.
PITFALL: Forgetting a break in a switch Statement
If you forget a break in a switch statement, the compiler does not issue an error mes-
sage. You will have written a syntactically correct switch statement, but it will not do
what you intended it to do. Notice the annotation in the example in the box entitled
“The switch Statement.”
The last case in a switch statement does not need a break , but it is a good idea to
include it nonetheless. That way, if a new case is added after the last case, you will not
forget to add a break (because it is already there). This advice about break statements
also applies to the default case when it is last. It is best to place the default case last, but
that is not required by the Java language, so there is always a possibility of somebody
adding a case after the default case.
Self-Test Exercises
9. What is the output produced by the following code?
char letter = 'B';
switch (letter)
{
case 'A':
case 'a':
System.out.println("Some kind of A.");
case 'B':
case 'b':
System.out.println("Some kind of B.");
break ;
default :
System.out.println("Something else.");
break ;
}
(continued)
 
Search WWH ::




Custom Search