java method to break out of for loop
break
continue
return
break statement
break is used to completely end a loop. Jump out of the loop. No matter what kind of loop, once a break is encountered in the loop body, the system will completely end the loop and start executing the code after the loop. break can not only end the loop in which it is located, but also end its outer loop. At this time, a label needs to be followed immediately after break. This label is used to identify an outer loop. A label in Java is an identifier followed by an English colon (:). And it must be placed before the loop statement to be effective.
public class BreakTest { public static void main(String[] args){ // 外层循环,outer作为标识符 outer: for (int i = 0 ; i < 5 ; i++ ){ // 内层循环 for (int j = 0; j < 3 ; j++ ){ System.out.println("i的值为:" + i + " j的值为:" + j); if (j == 1){ // 跳出outer标签所标识的循环。 break outer; } } } } }
continue statement
The function of the continue statement is to skip the remaining unexecuted statements in the loop body and immediately proceed to the next loop condition determination. It is understandable. Just to end this cycle.
Note: The continue statement does not terminate the entire loop.
The function of continue is somewhat similar to break. The difference is that continue only terminates this cycle and then starts the next cycle. And break completely terminates the loop.
public class ContinueTest { public static void main(String[] args){ // 一个简单的for循环 for (int i = 0; i < 3 ; i++ ){ System.out.println("i的值是" + i); if (i == 1){ // 忽略本次循环的剩下语句 continue; } System.out.println("continue后的输出语句"); } } }
break is to end the entire loop, continue is to end a single loop
return statement
The return keyword is not specifically used to jump out of the loop Yes, the function of return is to end a method. Once a return statement is executed within the loop body, the return statement will end the method and the loop will naturally end. Different from continue and break, return directly ends the entire method, no matter how many levels of loops this return is in.
public class ReturnTest { public static void main(String[] args){ // 一个简单的for循环 for (int i = 0; i < 3 ; i++ ){ System.out.println("i的值是" + i); if (i == 1){ return; } System.out.println("return后的输出语句"); } } }
The above is the detailed content of How to get out of for loop in java?. For more information, please follow other related articles on the PHP Chinese website!