0
0
Javaprogramming~5 mins

Break statement in Java

Choose your learning style9 modes available
Introduction

The break statement helps you stop a loop or switch case early when you want to exit before it finishes all steps.

When you find the item you are looking for in a list and want to stop searching.
When a condition inside a loop means you no longer need to continue looping.
When you want to exit a switch case after one case is done to avoid running other cases.
When you want to stop a game loop as soon as the player loses.
When you want to exit nested loops early after a certain condition is met.
Syntax
Java
break;

The break statement must be inside a loop (for, while, do-while) or a switch block.

It immediately stops the nearest enclosing loop or switch.

Examples
This loop prints numbers from 0 to 4 and stops when i equals 5.
Java
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
}
The break stops the switch after printing the matching day to avoid running other cases.
Java
int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Other day");
}
Sample Program

This program prints numbers from 1 to 5. When i reaches 6, the break stops the loop early.

Java
public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 6) {
                break;
            }
            System.out.println("Number: " + i);
        }
        System.out.println("Loop stopped early at i=6.");
    }
}
OutputSuccess
Important Notes

Using break can make your code easier to read by avoiding complex conditions in loops.

Be careful not to overuse break as it can sometimes make the flow harder to follow if used too much.

Summary

The break statement stops the nearest loop or switch immediately.

It is useful to exit early when a condition is met.

Remember to use break only inside loops or switch blocks.