switch Statements

The if and else statements are good for situations with only two possible conditions, but there are times when you have more than two options that need to be considered. With the preceding grade example, you saw that if and else statements can be chained to handle several different conditions.

Another way to do this is to use the switch statement. You can use it in a Java program to test for a variety of different conditions and respond accordingly. In the following example, the grade example has been rewritten with the switch statement to handle a complicated range of choices:

 switch (grade) { case 'A': System.out.println("You got an A. Great job!"); break; case 'B': System.out.println("You got a B. Good work!"); break; case ...

Get SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.