Home  >  Article  >  Java  >  How to break out of a loop in java

How to break out of a loop in java

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-11-12 16:12:576129browse

How to break out of a loop in java

The difference between break, continue and return:

break: The default is to jump out of the innermost loop, also It is the nearest loop where break is located.

continue: Terminate this cycle and continue the next cycle.

return: End the current method.

Simple test of 3-layer loop:

for (int i = 0; i < 3; i++) {
    for1:
    for (int j = 0; j <3; j++) {
        for2:
            for (int m = 0; m < 3; m++) {
                for3:
                    System.out.println(i+"--"+j+"--"+m);
            }
        }
    }

The results are as follows:

0--0--0
0--0--1
0--0--2
0--1--0
0--1--1
0--1--2
0--2--0
0--2--1
0--2--2
1--0--0
1--0--1
1--0--2
1--1--0
1--1--1
1--1--2
1--2--0
1--2--1
1--2--2
2--0--0
2--0--1
2--0--2
2--1--0
2--1--1
2--1--2
2--2--0
2--2--1
2--2--2

Simple test break:

for (int i = 0; i < 3; i++) {
    for1:
    for (int j = 0; j <3; j++) {
        for2:
            for (int m = 0; m < 3; m++) {
                for3:
                    if (m == 1) {
                        break;
                    }
                    System.out.println(i+"--"+j+"--"+m);
            }
        }
    }

The results are as follows:

0--0--0
0--1--0
0--2--0
1--0--0
1--1--0
1--2--0
2--0--0
2--1--0
2--2--0

Simple test continue:

for (int i = 0; i < 3; i++) {
    for1:
    for (int j = 0; j <3; j++) {
        for2:
            for (int m = 0; m < 3; m++) {
                for3:
                    if (m == 1) {
                        continue;
                    }
                    System.out.println(i+"--"+j+"--"+m);
            }
        }
    }

The results are as follows:

0--0--0
0--0--2
0--1--0
0--1--2
0--2--0
0--2--2
1--0--0
1--0--2
1--1--0
1--1--2
1--2--0
1--2--2
2--0--0
2--0--2
2--1--0
2--1--2
2--2--0
2--2--2

Simple test return:

for (int i = 0; i < 3; i++) {
    for1:
    for (int j = 0; j <3; j++) {
        for2:
            for (int m = 0; m < 3; m++) {
                for3:
                    if (m == 1) {
                        return;
                    }
                    System.out.println(i+"--"+j+"--"+m);
            }
        }
    }

The results are as follows:

0--0--0

php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!

The above is the detailed content of How to break out of a loop in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn