Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

break

In the following code, does the break statement break out of the if statement only or out of the for loop too?

I need it to break out of the loop too.

for (int i = 0; i < 5; i++) {
    if (i == temp)
        // do something
    else {
        temp = i;
        break;
    }
}
like image 782
darksky Avatar asked Sep 02 '11 22:09

darksky


People also ask

Does break statement break out of for loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute.

Does break statement break out of if statement?

breaks don't break if statements. A developer working on the C code used in the exchanges tried to use a break to break out of an if statement. But break s don't break out of if s. Instead, the program skipped an entire section of code and introduced a bug that interrupted 70 million phone calls over nine hours.

Is break only used for loops?

The break statement has no use in decison making statements. It is used only in loops, when you want to force termination from the loop and continue execution from the statement following the loop.

Does Break work for all loops?

The keyword break works only on the current loop. You can't break the outmost loop from any enclosed loop with a single break , you'll need to set a flag in order to break at start of each loop when it becomes non-null.


2 Answers

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.

like image 188
Oscar Gomez Avatar answered Oct 04 '22 14:10

Oscar Gomez


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.

like image 40
Oliver Charlesworth Avatar answered Oct 04 '22 13:10

Oliver Charlesworth