break Statement

In Java, the break statement is used to exit or terminate a loop prematurely. It can be used with various types of loops, including for, while, and do-while, as well as with switch statements. The break statement immediately exits the innermost loop or switch statement, allowing you to control the flow of your program.

Here’s the syntax for the break statement:

break;Code language: JavaScript (javascript)

Now, let’s look at some examples to understand how the break statement works:

Example 1: Using break in a for loop

Here’s an example that demonstrates how to use break statement in for loop:

Output:

public class BreakExample1 {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                // Exit the loop when i is 3
                break;
            }
            System.out.println("i = " + i);
        }
    }
}
D:\>javac BreakExample1.java

D:\>java BreakExample1 

i = 1
i = 2

In this example:

  • We have a for loop that iterates from 1 to 5.
  • Inside the loop, we use an if statement to check if i is equal to 3.
  • If i is indeed 3, the break statement is executed, causing an immediate exit from the loop.
  • As a result, only the numbers 1 and 2 are printed, and the loop terminates.

Example 2: Using break in a while loop

Here’s an example that demonstrates how to use break staement in while loop:

public class BreakExample2 {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            if (i == 3) {
                // Exit the loop when i is 3
                break;
            }
            System.out.println("i = " + i);
            i++;
        }
    }
}

Output:

D:\>javac BreakExample2.java

D:\>java BreakExample2

i = 1
i = 2

Example 3: Using break in a switch statement

Here’s an example that demonstrates how to use break statement in switch statement:

public class BreakExample3 {
    public static void main(String[] args) {
        int day = 3;
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break; // Exit the switch statement
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            default:
                System.out.println("Weekend");
        }
    }
}

Output:

D:\>javac BreakExample3.java

D:\>java BreakExample3
WednesdayCode language: CSS (css)
Scroll to Top