break
statement: Thebreak
statement is used to exit a loop prematurely. When thebreak
statement is encountered within a loop, the loop is immediately terminated, and the program continues with the next statement after the loop.
For example, consider the following code that uses a for loop to print the numbers from 1 to 5, but exits the loop prematurely if the number 3 is encountered:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println(i);
}
In this case, the break
statement is executed when i
is equal to 3, and the loop is terminated.
continue
statement: Thecontinue
statement is used to skip over a particular iteration of a loop. When thecontinue
statement is encountered within a loop, the current iteration is immediately terminated, and the loop continues with the next iteration.
For example, consider the following code that uses a for loop to print the numbers from 1 to 5, but skips over the number 3:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
In this case, the continue
statement is executed when i
is equal to 3, and the loop skips over that iteration.
Both break
and continue
statements are useful when you want to modify the default behavior of a loop based on certain conditions. However, they can also make your code harder to read and understand, especially when used excessively. Therefore, it is important to use them judiciously and only when necessary.