Lesson 9 | Breaking out of loops |
Objective | Learn how to break out of loops using the break statement. |
Breaking Out of Loops
If you recall from earlier in the module, every case
section of a switch
statement typically ends with a break
statement. To refresh your memory, take a look at the following example:
switch (score) {
case 1:
rating = "Poor";
break;
case 2:
rating = "Below Average";
break;
case 3:
rating = "Average";
break;
default:
rating = "Undefined";
The break
statement in this code is used to exit out of the switch
statement so that no other code is executed.
The break
statement can also be used in loops to exit out of a loop and bypass the loop condition.
Following is an example of getting out of an infinite loop with a break
statement:
int i = 0;
while (true) {
System.out.println("Keeps on going...");
if (++i > 99)
break;
}
When should a Java Developer make use of the break statement in his code?
A Java developer should make use of the break statement in their code when they want to exit early from a loop or switch statement, depending on certain conditions. The break statement helps in controlling the flow of execution and can make the code more efficient and easier to understand in some situations. Here are some scenarios where the break statement can be useful:
- Exiting a loop early: If a developer wants to exit a loop before its completion based on a specific condition, the break statement can be used. This can be helpful in avoiding unnecessary iterations and improving the efficiency of the code.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println("Current value of i: " + i);
}
- Breaking out of nested loops: In some cases, the developer may want to exit multiple levels of nested loops based on a condition. A labeled break statement can be used to achieve this. It allows breaking out of a specific outer loop by referencing the loop's label.
outerLoop:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i == 3 && j == 3) {
break outerLoop; // Exit the outer loop when i equals 3 and j equals 3
}
System.out.println("i: " + i + ", j: " + j);
}
}
- Exiting a switch statement: When using a switch statement, the break statement can be used to exit the switch block after executing the code for a specific case. Without the break statement, the code would continue executing the following cases until it encounters a break or reaches the end of the switch block.
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
In summary, a Java developer should make use of the break statement when they want to exit a loop or switch statement early based on certain conditions. It helps in controlling the flow of execution, making the code more efficient and easier to understand in specific situations.
break Statement
The effect of the break statement is to terminate the current loop, whether it be a while, for, for-each, or do-while statement. It is also used in the switch statement. The break statement passes control to the next statement following the loop. The break statement consists of the break keyword.
Consider the effect of the following statement sequence which repeatedly prompts the user for a command within an infinite loop.
The loop will be terminated when the user enters the Quit command:
String command;
while (true) {
System.out.print("Enter a command: ");
Scanner scanner = new Scanner(System.in);
command = scanner.next();
if ("Add".equals(command)) {
// Process Add command
}else if ("Subtract".equals(command)) {
// Process Subtract command
} else if ("Quit".equals(command)) {
break;
} else {
System.out.println("Invalid Command");
}
}
Notice how the equals method is used. The equals method is executed against the string literal and the command is used as its argument.
This approach avoids NullPointerException that will result if the command contains a null value. As the string literals are never null, this exception will never occur.
while-loop
Normally this while
loop would infinitely repeat due to the fixed loop condition of true.However, the break
statement offers a way out by breaking out of the loop after one hundred iterations (0-99
). The continue
statement is similar to the break
statement, and is used to skip to the next iteration of a loop.
The following example shows how to use a continue
statement to print only the odd numbers between 1
and 100
:
for (int i = 1; i <= 100; i++) {
if ((i % 2) != 1)
continue;
System.out.println(i);
}
Break Statement - Exercise