The Command.. break; in Java what if.?
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.
The break
statement has no effect on if statements. It only works on switch
, for
, while
and do
loops. So in your example the break would terminate the for
loop.
See this section and this section of the Java tutorial.
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;
}
}