Loop statements : break and continue

Case 1:

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.

Case 2:

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.

How break statement works?

Example 1: Java break statement

package com.test.test1;

public class TestBreak {
	public static void main(String[] args) {
		for (int i = 1; i <= 10; ++i) {
			if (i == 5) {
				break;
			}
			System.out.println(i);
		}
	}
}

When you run the program, the output will be:

1
2
3
4

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 :

package com.test.test1;

public class TestBreak {
	public static void main(String[] args) {
		int hrs = 1;
		int min = 1;
		while (hrs <= 6) {
			while (min <= 60) {
				if (hrs == 2) {
					System.out.println("About to break at hrs = 2");
					break;
				}
				System.out.println(hrs + ":" + min);
				min++;
			}
			hrs++;
			min = 1;
		}
	}
}

How continue statement works?

Example 1: Java continue statement

class Test {
   public static void main(String[] args) {
      
      for (int i = 1; i <= 10; ++i) {      
         if (i > 4 && i < 9) {
            continue;
         }      
         System.out.println(i);
      }   
   }
}

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:

1
2
​​​​3
4
9
10

In case of nested loops, continue skips the current iteration of innermost loop.

Problems:

Last updated