How to use java break statements

Source: Internet
Author: User

In the switch language, the break statement is used to terminate the execution of the switch statement. Run the first statement after the program switch statement.

In Java, you can add a bracket to each code block. A code block is usually enclosed by braces. Label format

The break statement has two forms: no label and no label. The unlabeled break statement is used to jump out of a single switch, for, while, or do-while loop, the break statements with labels are used to jump out of nested switch, for, while, or do-while statements.


BlockLabel: {codeBlock}

 

Call out while

Public class MainClass {

Public static void main (String [] args ){
Int I = 0;
While (true ){
System. out. println (I );
I ++;
If (I> 3 ){
Break;
        }
    }
  }

}

Terminate the for loop

Public class MainClass {
Public static void main (String [] args ){
Int count = 50;

For (int j = 1; j <count; j ++ ){
If (count % j = 0 ){
System. out. println ("Breaking !! ");
Break;
      }
    }
  }
}

Dual loop

Public class Main {
Public static void main (String args []) {

Int len = 100;
Int key = 50;
Int k = 0;
Out :{
For (int I = 0; I <len; I ++ ){
For (int j = 0; j <len; j ++ ){
If (I = key ){
Break out;
          }
K + = 1;
        }
      }
    }
System. out. println (k );
  }
}

More complex

Public class MainClass {
Public static void main (String [] args ){

OuterLoop: for (int I = 2; I ++ ){
For (int j = 2; j <I; j ++ ){
If (I % j = 0 ){
Continue OuterLoop;
        }
      }
System. out. println (I );
If (I = 37 ){
Break OuterLoop;
      }
    }
  }
}
 
2
3
5
7
11
13
17
19
23
29
31
37
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.