break and continue in loop

break and continue keywords are used inside while and for loops.

break is used to terminate the loop and break out of it where as continue just skips the particular iterator.

In the below example, we will loop through the names and break or continue when the name matches “Gyan”.

package com.java.core;

import java.util.Arrays;
import java.util.List;

public class BreakContinueExample {

    public static void main(String[] args) {

        List < String > names = Arrays.asList("Rochit", "Praveen", "Gyan", "Vivek", "Harsha");
        System.out.println("------------");
        System.out.println("Break Example");
        for (String name: names) {
            if (name.equals("Gyan")) break;
            System.out.println(name);
        }
        System.out.println("------------");

        System.out.println("Continue Example");
        for (String name: names) {
            if (name.equals("Gyan")) continue;
            System.out.println(name);
        }
        System.out.println("------------");

    }

}
------------
Break Example
Rochit
Praveen
------------
Continue Example
Rochit
Praveen
Vivek
Harsha
------------

Leave a Reply

Your email address will not be published. Required fields are marked *