Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

break
loop
java
communitycreator

What is a break in Java?

Andreas Lundblad

The break keyword can be used to exit a loop in the middle of an iteration.

widget

Example

Here’s a simple loop that iterates through an array and breaks if the string "quit" is found.

class BreakLoop {
    public static void main( String args[] ) {
        String[] arr = {"Edpresso", "shots", "quit", "continue"};

        for (String s : arr){
          if (s == "quit"){
            break;
          }
          System.out.println(s);
        }
    }
}

The first two strings in the array are printed without any issues. However, when "quit" is encountered, the loop breaks and the remaining strings are not printed.

break works precisely the same way for while and do...while loops.

Nested Loops

By default, break only breaks the immediately enclosing loop. To break out of an outer loop, use​ labeled​ statements.

widget

RELATED TAGS

break
loop
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring