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?" ...
Get Sams Teach Yourself Java™ in 24 Hours, Sixth 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.