Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0061 break to Exit a Loop

When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example: public class Main { public static void main(String args[]) { for (int i = 0; i < 100; i++) { if (i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } } This program generates the following output: i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9 Loop complete. The break statement can be used with while loop as well. For example, here is the preceding program coded by use of a while loop. public class Main { public static void main(String args[]) { int i = 0; while (i < 100) { if (i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); i++; } System.out.println("Loop complete."); } } The output: i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9 Loop complete. The break statement can be used with infinite loops. public class Main { public static void main(String args[]) { int i = 0; while (true) { if (i == 10){ break; // terminate loop if i is 10 } System.out.println("i: " + i); i++; } System.out.println("Loop complete."); } } The output: i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9 Loop complete. When used inside a set of nested loops, the break statement will only break out of the inner-most loop. For example: public class Main { public static void main(String args[]) { for (int i = 0; i < 5; i++) { System.out.print("Pass " + i + ": "); for (int j = 0; j < 100; j++) { if (j == 10) break; // terminate loop if j is 10 System.out.print(j + " "); } System.out.println(); } System.out.println("Loops complete."); } } This program generates the following output: Pass 0: 0 1 2 3 4 5 6 7 8 9 Pass 1: 0 1 2 3 4 5 6 7 8 9 Pass 2: 0 1 2 3 4 5 6 7 8 9 Pass 3: 0 1 2 3 4 5 6 7 8 9 Pass 4: 0 1 2 3 4 5 6 7 8 9 Loops complete. The break that terminates a switch statement affects only that switch statement and not any enclosing loops. public class Main { public static void main(String args[]) { for (int i = 0; i < 6; i++) switch (i) { case 1: System.out.println("i is one."); for (int j = 0; j < 5; j++) { System.out.println("j is " + j); } break; case 2: System.out.println("i is two."); break; default: System.out.println("i is greater than 3."); } } } The output: i is greater than 3. i is one. j is 0 j is 1 j is 2 j is 3 j is 4 i is two. i is greater than 3. i is greater than 3. i is greater than 3.