Why does Java allow for labeled breaks on arbitrary statements?

前端 未结 9 2060
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 13:16

I just learned today that the following Java code is perfectly legal:

myBlock: {
    /* ... code ... */

    if (doneExecutingThisBlock())
        break myBlock;         


        
9条回答
  •  轮回少年
    2021-02-07 13:54

    The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.

    It seems to be useful to exit nested loops. See http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

    It's semantically the same as is there a equivalent of Java's labelled break in C# or a workaround

提交回复
热议问题