Does the break statement break out of loops or only out of if statements?

It also goes out of the loop.

You can also use labeled breaks that can break out of outer loops (and arbitrary code blocks).

looplbl: for(int i=;i<;i++){

    if (i == temp)
        // do something
    else {
        temp = i;
        break looplbl;
    }
}

An unlabelled break only breaks out of the enclosing switch, for, while or do-while construct. It does not take if statements into account.

See http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html for more details.


That would break out of the for loop. In fact break only makes sense when talking about loops, since they break from the loop entirely, while continue only goes to the next iteration.


It breaks the loop, but why not explicitly put the condition in the for itself? It would be more readable and you would not have to write the if statement at all

(if i==temp then temp = i is totally pointless)

Tags:

Java

Break