Break || Continue || Java example

Java break and continue :

The java keywords break and continue are used to stop a iteration or to skip a iteration based on the provided condition.

Let’s see the real time usage of java break and continue

 

break :

When you are looping through a iteration and want to stop the complete iteration when a certain condition is satisfied then you can use this keyword.

 

Consider a class abcd and try to implement break keyword by using for loop

 

when the loop iterates and reaches 5 it will break the loop and comes out.

if(i == 5)
    break;

 

public class abcd {

    public static void main(String args[]){

        for(int i = 1; i< 10; i++){

            if(i == 5)
                break;

            System.out.println(i);
        }
    }
}

 

java break and continue

 

continue :

The keyword continue is used t skip a iteration and continue later iterations as usually.

Consider the same looping example where we will continue at iteration 5

if(i == 5)
    continue;

 

public class abcd {

    public static void main(String args[]){

        for(int i = 1; i< 10; i++){

            if(i == 5)
                continue;

            System.out.println(i);
        }
    }
}

 

java break and continue

 

If you wonder what if we use continue in place of break ???

break will completely stops the iterations while continue provides the same output but will continue iterating loop until condition is satisfied.

Show Buttons
Hide Buttons
Read previous post:
Exception Handling || Java example

  Java exceptional handling : Java exceptional handling, In java Exceptions occur during programming resulting in abnormal termination of program.A...

Close