The Command.. break; in Java what if.?

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++) {
    if (condition) {
        statement;
        break;
    }
}

Solution 1:

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.

Solution 2:

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;
   }
}