Loop statements : break and continue
Last updated
Last updated
Imagine that you've defined a loop to iterate through a list of managers, and you're looking for at least one manager whose name starts with the letter D.You'd like to exit the loop after you find the first match, but how? You can do this by using the break statement in your loop.
Now imagine that you want to iterate through all the folders on your laptop and scan any files larger than 10 MB for viruses. If all those files are found to be OK, you want to upload them to a server.But what if you'd like to skip the steps of virus checking and file uploading for file sizes less than 10 MB yet still proceed with the remaining files on your laptop? You can! You'd use the continue statement in your loop.
When you run the program, the output will be:
In the above program, when the value of i becomes 5, expression i == 5
inside the parenthesis of if
statement is evaluated to true
. Then, The break
statement is executed terminates the for loop.
In case of nested loops, break
terminates the innermost loop.
Here, the break statement terminates the innermost while
loop, and control jumps to the outer loop.
Problem: Find the output :
When the value of i becomes more than 4 and less than 9, continue
statement is exectued, which skips the execution of System.out.println(i);
statement.
When you run the program, the output will be:
In case of nested loops, continue
skips the current iteration of innermost loop.