java符合条件跳出循环_Java如何知道跳出循环的位置?

I don’t understand how the break statement “knows” that it is within a loop for it to exit out of in the first place.

break语句不知道它在一个开关或循环语句中。编译器验证break语句是否在一个开关或循环语句中。如果遇到不在循环语句中的中断语句,它将发出编译时错误。

If no switch, while, do, or for statement in the immediately enclosing method, constructor, or initializer contains the break statement, a compile-time error occurs.

如果编译器能够验证中断语句是否在一个开关或循环语句中,那么它将发出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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值