Break statement

A break statement is used to exit any conditional statement. It terminates the loop immediately, and program control moves to the next statement.

Syntax

break;

Use case demonstrating break statement with while loop

public class Sample {
    public static void main(String[] args) {
        //while loop 
        int i = 1;
        while (i <= 10) {
            if (i == 5) {
                //using break statement 
                break;//it will break the loop 
            }
            System.out.println(i);
            i++;
        }
    }
}

 

Output:

1
2
3
4

 

Use case demonstrating break statement with for loop and inner loop

If the break statement is used in the inner loop only it will exit the inner loops

public class Sample {
    public static void main(String[] args) {
        //using for loop 
        for (int i = 1; i <= 10; i++) {
            if (i == 6) {
                //breaking the loop 
                break;
            }
            System.out.println(i);
        }
    }
}

 

Output:

1
2
3
4
5

 

Use case demonstrating break statement with switch case

Break keyword is used to break the switch block and avoid execution of the rest of the code

public class Usecase {
    public static void main(String[] args) {
        int x = 2;
        switch (x) {
            case 1:
                System.out.println("value of x is 1");
                break;
            case 2:
                System.out.println("value of x is 2");
                break;
            default:
                System.out.println("value of x is 0");
        }
    }
}

 

Output:

value of x is 2
 

 

Related Tutorials

Map