Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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;     } } 
like image 658
wam090 Avatar asked Nov 11 '10 12:11

wam090


People also ask

What does break do in IF statement Java?

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.

Can we use break in if condition?

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.

What is break called in Java?

Break Statement is a loop control statement that is used to terminate the loop.

Do breaks break if statements?

A break breaks from a loop and not from if statement.


2 Answers

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.

like image 105
brain Avatar answered Sep 22 '22 02:09

brain


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;    } } 
like image 40
semicontinuity Avatar answered Sep 20 '22 02:09

semicontinuity