[java] Is it bad practice to use break to exit a loop in Java?

I was wondering if it is a "bad practice" to use a break statement to exit a loop instead of fulfilling the loop condition?

I do not have enough insight in Java and the JVM to know how a loop is handled, so I was wondering if I was overlooking something critical by doing so.

The focus of this question: is there a specific performance overhead?

This question is related to java loops jvm break

The answer is


In my opinion a For loop should be used when a fixed amount of iterations will be done and they won't be stopped before every iteration has been completed. In the other case where you want to quit earlier I prefer to use a While loop. Even if you read those two little words it seems more logical. Some examples:

for (int i=0;i<10;i++) {
    System.out.println(i);
}

When I read this code quickly I will know for sure it will print out 10 lines and then go on.

for (int i=0;i<10;i++) {
    if (someCondition) break;
    System.out.println(i);
}

This one is already less clear to me. Why would you first state you will take 10 iterations, but then inside the loop add some extra conditions to stop sooner?

I prefer the previous example written in this way (even when it's a little more verbose, but that's only with 1 line more):

int i=0;
while (i<10 && !someCondition) {
    System.out.println(i);
    i++;
}

Everyone who will read this code will see immediatly that there is an extra condition that might terminate the loop earlier.

Ofcourse in very small loops you can always discuss that every programmer will notice the break statement. But I can tell from my own experience that in larger loops those breaks can be overseen. (And that brings us to another topic to start splitting up code in smaller chunks)


Using break in loops can be perfectly legitimate and it can even be the only way to solve some problems.

However, it's bad reputation comes from the fact that new programmers usually abuse it, leading to confusing code, especially by using break to stop the loop in conditions that could have been written in the loop condition statement in the first place.


While its not bad practice to use break and there are many excellent uses for it, it should not be all you rely upon. Almost any use of a break can be written into the loop condition. Code is far more readable when real conditions are used, but in the case of a long-running or infinite loop, breaks make perfect sense. They also make sense when searching for data, as shown above.


It isn't bad practice, but it can make code less readable. One useful refactoring to work around this is to move the loop to a separate method, and then use a return statement instead of a break, for example this (example lifted from @Chris's answer):

String item;

for(int x = 0; x < 10; x++)
{
    // Linear search.
    if(array[x].equals("Item I am looking for"))
    {
        //you've found the item. Let's stop.
        item = array[x];
        break; 
    }
}

can be refactored (using extract method) to this:

public String searchForItem(String itemIamLookingFor)
{
    for(int x = 0; x < 10; x++)
    {
        if(array[x].equals(itemIamLookingFor))
        {
            return array[x];
        }
    }
}

Which when called from the surrounding code can prove to be more readable.


The JLS specifies a break is an abnormal termination of a loop. However, just because it is considered abnormal does not mean that it is not used in many different code examples, projects, products, space shuttles, etc. The JVM specification does not state either an existence or absence of a performance loss, though it is clear code execution will continue after the loop.

However, code readability can suffer with odd breaks. If you're sticking a break in a complex if statement surrounded by side effects and odd cleanup code, with possibly a multilevel break with a label(or worse, with a strange set of exit conditions one after the other), it's not going to be easy to read for anyone.

If you want to break your loop by forcing the iteration variable to be outside the iteration range, or by otherwise introducing a not-necessarily-direct way of exiting, it's less readable than break.

However, looping extra times in an empty manner is almost always bad practice as it takes extra iterations and may be unclear.


If you start to do something like this, then I would say it starts to get a bit strange and you're better off moving it to a seperate method that returns a result upon the matchedCondition.

boolean matched = false;
for(int i = 0; i < 10; i++) {
    for(int j = 0; j < 10; j++) {
        if(matchedCondition) {
            matched = true;
            break;
        }
    }
    if(matched) {
        break;
    }
}

To elaborate on how to clean up the above code, you can refactor, moving the code to a function that returns instead of using breaks. This is in general, better dealing with complex/messy breaks.

public boolean  matches()
    for(int i = 0; i < 10; i++) {
        for(int j = 0; j < 10; j++) {
            if(matchedCondition) {
                return true;
            }
        }
    }
    return false;
}

However for something simple like my below example. By all means use break!

for(int i = 0; i < 10; i++) {
    if(wereDoneHere()) { // we're done, break.
        break;
    }
}

And changing the conditions, in the above case i, and j's value, you would just make the code really hard to read. Also there could be a case where the upper limits (10 in the example) are variables so then it would be even harder to guess what value to set it to in order to exit the loop. You could of course just set i and j to Integer.MAX_VALUE, but I think you can see this starts to get messy very quickly. :)


If you know in advance where the loop will have to stop, it will probably improve code readability to state the condition in the for, while, or `do-while loop.

Otherwise, that's the exact use case for break.


No, it is not a bad practice to break out of a loop when if certain desired condition is reached(like a match is found). Many times, you may want to stop iterations because you have already achieved what you want, and there is no point iterating further. But, be careful to make sure you are not accidentally missing something or breaking out when not required.

This can also add to performance improvement if you break the loop, instead of iterating over thousands of records even if the purpose of the loop is complete(i.e. may be to match required record is already done).

Example :

for (int j = 0; j < type.size(); j++) {
        if (condition) {
            // do stuff after which you want 

            break; // stop further iteration
        }

}

No, it is not a bad practice. It is the most easiest and efficient way.


There are a number of common situations for which break is the most natural way to express the algorithm. They are called "loop-and-a-half" constructs; the paradigm example is

while (true) {
    item = stream.next();
    if (item == EOF)
        break;
    process(item);
}

If you can't use break for this you have to repeat yourself instead:

item = stream.next();
while (item != EOF) {
    process(item);
    item = stream.next();
}

It is generally agreed that this is worse.

Similarly, for continue, there is a common pattern that looks like this:

for (item in list) {
    if (ignore_p(item))
        continue;
    if (trivial_p(item)) {
        process_trivial(item);
        continue;
    }
    process_complicated(item);
}

This is often more readable than the alternative with chained else if, particularly when process_complicated is more than just one function call.

Further reading: Loop Exits and Structured Programming: Reopening the Debate


Using break, just as practically any other language feature, can be a bad practice, within a specific context, where you are clearly misusing it. But some very important idioms cannot be coded without it, or at least would result in far less readable code. In those cases, break is the way to go.

In other words, don't listen to any blanket, unqualified advice—about break or anything else. It is not once that I've seen code totally emaciated just to literally enforce a "good practice".

Regarding your concern about performance overhead, there is absolutely none. At the bytecode level there are no explicit loop constructs anyway: all flow control is implemented in terms of conditional jumps.


break and continue breaks the readability for the reader, although it's often useful. Not as much as "goto" concept, but almost.

Besides, if you take some new languages like Scala (inspired by Java and functional programming languages like Ocaml), you will notice that break and continue simply disappeared.

Especially in functional programming, this style of code is avoided:

Why scala doesn't support break and continue?

To sum up: break and continueare widely used in Java for an imperative style, but for any coders that used to practice functional programming, it might be.. weird.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to jvm

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6 How can I get a random number in Kotlin? Kotlin unresolved reference in IntelliJ Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8? Android Gradle Could not reserve enough space for object heap Android java.exe finished with non-zero exit value 1 Android Studio Gradle project "Unable to start the daemon process /initialization of VM" Android Studio - No JVM Installation found Android Studio error: "Environment variable does not point to a valid JVM installation" Installing Android Studio, does not point to a valid JVM installation error

Examples related to break

How to break a while loop from an if condition inside the while loop? illegal use of break statement; javascript How can I use break or continue within for loop in Twig template? break statement in "if else" - java Regarding Java switch statements - using return and omitting breaks in each case Is it bad practice to use break to exit a loop in Java? break/exit script Breaking out of a for loop in Java How to break out of while loop in Python? How to kill a while loop with a keystroke?