O'Reilly logo

Sams Teach Yourself Java™ in 24 Hours, Sixth Edition by Rogers Cadenhead

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

switch Statements

The if and else statements are good for situations with two possible conditions, but there are times when you have more than two conditions.

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 with the switch statement, which can test for a variety of different conditions and respond accordingly. In the following code, the grading example has been rewritten with a switch statement:

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 'C':        System.out.println("You got a C. What went wrong?" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required