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!