Branching statements
You have already seen the branching statements break
andreturn
in our examples. We will define and discuss them and the third member of the group—the branching statementcontinue
—in this section.
Break and labeled break
As you have probably noticed, the break
statement is essential for the switch...case
selection statements to be able to work (see the switch...case section for more information). If included in the execution block of an iteration statement, it causes the for
or while
statement to terminate immediately.
It is widely used in iteration statements while searching for a particular element in an array or collection. To demonstrate how it works, let's assume, for example, that we need to find a certain person by age and name among the students and teachers of a community college. Let's first create the classes Person
, Student
, and Teacher
:
class Person{ private int age; private String name; public Person(int age, String name) { this.age = age; this.name...