Learn Java Basics
About Lesson

In Java, break and continue are two control flow statements that can be used in loops to alter their normal execution. Here’s how they work:

1. Break statement:

The break statement is used to exit a loop prematurely. When the break statement is encountered in a loop, the loop is immediately terminated, and the program execution continues with the statement immediately following the loop. Here’s an example:

for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
System.out.print(i);
}

In this example, the loop will terminate when i is equal to 5, and the program execution will continue with the statement immediately following the loop. The output of this program will be:

1
2
3
4

2. Continue statement:

The continue statement is used to skip over the current iteration of a loop and continue with the next iteration. When the continue statement is encountered in a loop, the current iteration of the loop is immediately terminated, and the program execution continues with the next iteration of the loop. Here’s an example:

for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
continue;
}
System.out.print(i);
}

In this example, the loop will skip over the iteration when i is equal to 5, and the program execution will continue with the next iteration of the loop. The output of this program will be:

1
2
3
4
6
7
8
9
10

Both break and continue statements can also be used in while and do-while loops, in addition to for loops. These statements are useful when you need to alter the normal execution of a loop based on certain conditions.


Join the conversation