Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 186

Exiting with break Statements

Оглавление

Taking a look at our previous printDayOfWeek() implementation, you'll see a break statement at the end of each case and default section. A break statement terminates the switch statement and returns flow control to the enclosing process. Put simply, it ends the switch statement immediately.

The break statements are optional, but without them the code will execute every branch following a matching case statement, including any default statements it finds. Without break statements in each branch, the order of case and default statements is now extremely important. What do you think the following prints when printSeason(2) is called?

public void printSeason(int month) { switch(month) { case 1, 2, 3: System.out.print("Winter"); case 4, 5, 6: System.out.print("Spring"); default: System.out.print("Unknown"); case 7, 8, 9: System.out.print("Summer"); case 10, 11, 12: System.out.print("Fall"); } }

It prints everything!

WinterSpringUnknownSummerFall

It matches the first case statement and executes all of the branches in the order they are found, including the default statement. It is common, although certainly not required, to use a break statement after every case statement.

The exam creators are fond of switch examples that are missing break statements! When evaluating switch statements on the exam, always consider that multiple branches may be visited in a single execution.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх