Why does Java allow for labeled breaks on arbitrary statements?

前端 未结 9 2059
爱一瞬间的悲伤
爱一瞬间的悲伤 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:51

    Adding to Stephen C's answer, if (something) you cannot break out of a nested loop. These situations do happen in numerical algorithms. One simple example here - you cannot break out of the i-loop without the named for. Hope this helps.

    public class JBreak  {
    
        private int brj;
    
        public JBreak (String arg) {
            brj = Integer.parseInt (arg);       
        }
    
        public void print () {
            jbreak:
            for (int i = 1 ; i < 3 ; i++) {
                for (int j = 0 ; j < 5 ; j++) {
                    if ((i*j) == brj)
                        break jbreak;
                    System.out.println ("i,j: " + i + "," + j);
        }}}
    
        public static void main (String[] args) {
            new JBreak(args[0]).print();
    }}
    

提交回复
热议问题