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;
}
}
That would break out of the for loop. In fact
break
only makes sense when talking aboutloops
, since they break from theloop
entirely, whilecontinue
only goes to the nextiteration
.An unlabelled
break
only breaks out of the enclosingswitch
,for
,while
ordo-while
construct. It does not takeif
statements into account.See http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html for more details.
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)
break
is to break out of any loop.It will break out of the loop always.
Break never refers to if/else statements. It only refers to loops (if/while) and switch statements.