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

后端 未结 8 502
走了就别回头了
走了就别回头了 2021-02-03 17:50

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++) {
           


        
相关标签:
8条回答
  • 2021-02-03 18:05

    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.

    0 讨论(0)
  • 2021-02-03 18:07

    It will stop the loop.

    0 讨论(0)
  • 2021-02-03 18:10

    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.

    0 讨论(0)
  • 2021-02-03 18:14
    for (int i = 0; i < array.length; i++) {
        jumpIf: if (condition) {
            statement;
            break jumpIf;
        }
    }
    
    0 讨论(0)
  • 2021-02-03 18:17

    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;
       }
    }
    
    0 讨论(0)
  • 2021-02-03 18:17

    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.

    0 讨论(0)
提交回复
热议问题