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?" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access