Net-informations.com
SiteMap  | About    

break and continue statement

It is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression. In such cases we can use break statements in Java. Please note that Java does not provide Go To statement like other programming languages e.g. C, C++ (The Java keyword list specifies the goto keyword, but it is marked as "not used").

Break statement

The break statement is used with the conditional switch statement and with the do, for, and while loop statements. When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.

Syntax:

break statements in java

As seen in the above image, the break statement ends execution of the nearest enclosing loop or conditional statement in which it appears. Control passes to the statement that follows the end of the statement, if any.

Example:

Output:

In the above program, when cnt==3, the break statement executed and immediately terminated the while loop and the program control resumes at the next statement.

break statement in for loop

Output:

Continue statement

Continue statement works like break but instead of forcing termination, it forces the next iteration of the loop to take place and skipping the rest of the code. Continue statement is mostly used inside loops, whenever it is encountered inside a loop, either conditionally or unconditionally, transfers control to the next iteration of either the current loop or an enclosing labelled loop.

Syntax:

continue statement in java

As seen in the above image, the continue statement ends current flow of execution and control directly jumps to the beginning of the loop for next iteration.

Example:

Output:

In the baove program, we can see in the output the 3 is missing. It is because when cnt==3 the loop encounter the continue statement and control go back to start of the loop.

continue statement in for loop

Output:









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.