そもそも break ステートメントがループ内にあることを「認識」する方法がわかりません。
ステートメントは、or ループ ステートメントbreak
内にあることを認識していません。switch
コンパイラは、ステートメントがor ループ ステートメント内にあることを確認します。ループ ステートメント内にないステートメントに遭遇すると、コンパイル時エラーが発生します。break
switch
break
すぐ外側のメソッド、コンストラクター、または初期化子のswitch
、while
、do
、またはfor
ステートメントに break ステートメントが含まれていない場合、コンパイル時エラーが発生します。
break
ステートメントが or ループ ステートメント内にあることをコンパイラが確認できる場合、コンパイラはswitch
JVM 命令を発行して、最も近い外側のループの直後の最初のステートメントに突然ジャンプします。
したがって:
for(int i = 0; i < 10; i++) {
if(i % 2 == 0) {
break;
}
}
コンパイラによって次のように変換されます。
0: iconst_0 # push integer 0 onto stack
1: istore_1 # store top of stack in local 1 as integer
# i = 0
2: iload_1 # push integer in local 1 onto stack
3: bipush 10 # push integer 10 onto stack
5: if_icmpge 23 # pop and compare top two (as integers), jump if first >= second
# if i >= 10, end for
8: iload_1 # push integer in local 1 onto stack
9: iconst_2 # push integer 2 onto stack
10: irem # pop top two and computes first % second and pushes result
# i % 2
11: ifne 17 # pop top (as integer) and jump if not zero to 17
# if(i % 2 == 0)
14: goto 23 # this is the break statement
17: iinc 1, 1 # increment local 1 by 1
# i++
20: goto 2 # go to top of loop
# loop
23: return # end of loop body