What if we have an if statement inside a for loop, would it stop the loop or the if condition...
Example:
for (int i = 0; i < array.length; i++) {
The selected answer is almost right. if break
statement be mixed by label
then it can be used in if
statement without needing to be in a loop. The following code is completely valid, compiles and runs.
public class Test {
public static void main(String[] args) {
int i=0;
label:if(i>2){
break label;
}
}
}
However if we remove the label, it fails to compile.
It will stop the loop.
Once the condition is met and the statement has successfully been executed (let's assuming no exception is thrown), then the break
exits from the loop.
for (int i = 0; i < array.length; i++) {
jumpIf: if (condition) {
statement;
break jumpIf;
}
}
You can break out of just 'if' statement also, if you wish, it may make sense in such a scenario:
for(int i = 0; i<array.length; i++)
{
CHECK:
if(condition)
{
statement;
if (another_condition) break CHECK;
another_statement;
if (yet_another_condition) break CHECK;
another_statement;
}
}
you can also break out of labeled {} statement:
for(int i = 0; i<array.length; i++)
{
CHECK:
{
statement;
if (another_condition) break CHECK;
another_statement;
if (yet_another_condition) break CHECK;
another_statement;
}
}
a break
statement (and its companion, 'continue', as well) works on a surrounding loop. An if
-statement is not a loop. So to answer your question: the break
in your code example will jump out of the for
-loop.