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; } }
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
The if statement is not a loop . it is either not exected at all or exectuted just once. So it absolutely makes no sense to put a break inside the body of if.
Break Statement is a loop control statement that is used to terminate the loop.
A break breaks from a loop and not from if statement.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With