Does the break statement break out of loops or onl

2019-01-24 06:16发布

In the following code, does the break statement break out of the if statement only or out of the for loop too?

I need it to break out of the loop too.

for (int i = 0; i < 5; i++) {
    if (i == temp)
        // do something
    else {
        temp = i;
        break;
    }
}

标签: java break
8条回答
等我变得足够好
2楼-- · 2019-01-24 06:55

It also goes out of the loop.

You can also use labeled breaks that can break out of outer loops (and arbitrary code blocks).

looplbl: for(int i=;i<;i++){

    if (i == temp)
        // do something
    else {
        temp = i;
        break looplbl;
    }
}
查看更多
Root(大扎)
3楼-- · 2019-01-24 06:55

Generally break statement breaks out of loops (for, while, and do...while) and switch statements.

In Java there are 2 variant of break.

1. Labeled break

It break outs of the outer loop where you put the lable.

breakThis: for(...){
   for(...){
      ... 
      break breakThis;  // breaks the outer for loop
   }
}

2. Unlabeled break

It is the statement you used in your question.

It breaks the loop in which it is written. Generally inner loop.

查看更多
登录 后发表回答