Ways to jump out of a for loop in Java

Source: Internet
Author: User

Now, in Java, if you want to jump out of a for loop, there are generally two ways to do this: break and continue.

Break is to jump out of the current for loop, as shown in the following code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Public class Rectest {

/**

* @param args

*/ 

public static void Main (String[] args) {

for(int i=0; i< ; i++) {

if(i==5) {

break;

}  

System.out.print (i+"");

}  

}  

}

Output:0 1 2 3 4

In other words, break jumps out (terminates) the current loop. Continue is to jump out of the current loop and start the next loop as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Public class Rectest {

/**

* @param args

*/ 

public static void Main (String[] args) {

for (int i = 0; i < i++) {

if (i = = 5) {

continue;

}  

System.out.print (i+"");

}  

}  

}

Output:0 1 2 3 4 6 7 8 9

The above two methods do not jump out of the multilayer loop, if you need to jump out of the multi-layer loop, you need to use a label, define a label tag, and then where you need to jump, with the break label on the line, the code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

Public class Rectest {

/**

* @param args

*/ 

public static void Main (String[] args) {

Loop: for (int i = 0; i < i++) {

for (int j = 0; j < ; j + +) {

for (int k = 0; k < k++) {

for (int h = 0; h < h++) {

if (h = = 6) {

break Loop;

}  

System.out.print (h);

}  

}  

}  

}  

System.out.println ("\ni ' m here!"  );

}  

}

Output:

012345

I ' m here!

Want to learn more about Java, you can click on the small peak online Java 0 Foundation ? To learn. More Java Learning courses, you can focus on e mentor .

Ways to jump out of a for loop in Java

Related Article

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.