wam090
wam090

Reputation: 2873

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

Upvotes: 51

Views: 86774

Answers (8)

PedroZGZ
PedroZGZ

Reputation: 1

for (int i = 0; i < array.length; i++) {
    jumpIf: if (condition) {
        statement;
        break jumpIf;
    }
}

Upvotes: 0

Reza
Reza

Reputation: 1556

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.

Upvotes: 9

semicontinuity
semicontinuity

Reputation: 129

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

Upvotes: 12

brain
brain

Reputation: 5546

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.

Upvotes: 104

Jeen Broekstra
Jeen Broekstra

Reputation: 22053

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.

Upvotes: 3

Buhake Sindi
Buhake Sindi

Reputation: 89209

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.

Upvotes: 0

Nico Huysamen
Nico Huysamen

Reputation: 10427

The break command inside the IF statement will exit the FOR loop.

Upvotes: 3

Cameron Skinner
Cameron Skinner

Reputation: 54536

It will stop the loop.

Upvotes: 3

Related Questions