JAVA Tutorial
The break statement was already utilized in a previous chapter of this lesson. A switch statement was “jumped out” of using it.
Another way to exit a loop is with the break statement.
In this example, the loop is terminated when i reaches 4.
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 4:
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
In while loops, you may also use break and continue:
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
if (i == 4) {
break;
}
}
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
System.out.println(i);
i++;
}
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.