Java Reference
In-Depth Information
if (emp.equals(employeeID)){
return true;
}
}
return false;
}
As soon as the specified
employeeID
is found, the Boolean
true
will be returned. This will interrupt
the search, whether it is the first string in the array, the last string, or anywhere in between. In this
way, the flow of the program is controlled by the
return
statement.
It is also possible to use the
return
statement in the same way, but with a
void
method. In this case,
the method will be interrupted, but no value will be returned.
import java.util.ArrayList;
static ArrayList<String> employeeList = new ArrayList< >();
//a method to add new Employees to the Employee array
static void addNewEmployee(String employeeID){
if (employeeList.contains(employeeID)){
return; //employee already exists
}
employeeList.add(employeeID);
}
In this example, if the employee is found in the
ArrayList
, then there is no need to put her into it.
Therefore, the code returns nothing as soon as the employee is found and then exits the method.
Controlling with the break Keyword
The
break
keyword also interrupts the execution of the current block of code. You already saw
this keyword used as part of the
switch
statement. It can also be used, in a similar way, with loop
structures. A
break
could be thought of as a softer interruption than
return
, as the method con-
tinues to execute, just in a different place after breaking out of the current block. If
break
occurs
as part of an iterative loop, the loop containing the
break
statement will be stopped and it will
not complete any further iterations. In the following example, the use of the
break
keyword to
exit a loop is shown.
//array of employee ID numbers, stored as Strings
static String[] employees;
//method to search for a specified employee ID
static void findEmployee(String employeeID){
String myString = employeeID + " was not found.";
for (String emp : employees){
if (emp.equals(employeeID)){
myString = employeeID + " was found.";
break;
}
}
System.out.println(myString);
}
Search WWH ::
Custom Search