break and continue: java break label and continue label with examples
Java break and continue:
Java break and continue:- This article is about how to get out of loops early (break) or skip the rest of the loop body (continue).
break
break aborts a loop prematurely. The program will start with the first Command continued after the end of the loop. The following code performs calculations in a loop. As soon as the result is a Calculation is less than 0 for the first time, the loop is aborted.
1 2 3 4 5 |
for (int i = 0; i <100; i ++) { result = computeSomething(i); if (result <0) break; } |
Continue:
continue skips the remaining instructions of the loop body and then continue the loop. For a for loop, continue executes the increment statement, and then uses the condition tested whether the loop body is run through again. The following For example, a two-part calculation is performed in a loop. If the first intermediate result (n) is less than 0, the second Part of the calculation is omitted. The loop is set to the next value for i.
1 2 3 4 5 6 |
for(int i=0; i <100; i++) { n = calculated part1 (i); if(n<0) continue ; m = calculated part2 (n); } |
Java break and continue in nested loops:
With nested loops, java break and continue to apply by default only for the innermost loop. To jump out of multiple loop levels or the program with the increment instruction of an outerTo continue loop, the loop in question must have a label (a label). This is one Name followed by a colon. The mark must be in front of the concerned Loop. You can now at break or continue can be used to clarify which loop the command applies to should:
1 2 3 4 5 6 7 |
: for (x = 0; x <10; x ++) { for (y = 0; y <10; y ++) { if (computeSomething (x, y) <0) break xloop; // cancel both loops } } |
outbreak with break and restarting with continue:
If a break-in-a-loop is used within a for, while, or do-while statement, the loop run is terminated and the Processing continued at the first statement after the loop. That an endless loop can be terminated with break is useful, when a condition occurs that determines the end of the loop. The can be transferred perfectly to our number-guessing game:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class demo{ public static void main(String[] args) { int number = (int) (Math.random() * 5 + 1); while (true) { System.out.println( "What number do I think is between 1 and 5?" ); int guess = new java.util.Scanner(System.in).nextInt(); if ( number == guess ) { System.out.println( "Super typed!" ); break; // End of loop } else if ( number > guess ) System.out.println( "Nah, my number is bigger than yours!" ); else if ( number < guess ) System.out.println( "Nah, my number is smaller than yours!" ); } } } |
output:
The case differentiation determines whether the user has to re-enter a re-guess the loop run or whether the tip was correct; then the break statement terminates the spook.
Flags or break:
break can be used well to get out of a loop prematurely without using flags. Let me give you an example of what should be avoided:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
boolean endFlag = false; do { if (condition) { ... endFlag = true; } } while ( OtherCondition && ! endFlag ); Instead, we write: do { if (condition) { ... break; } } while ( OtherCondition ); |
The alternative solution is of course a difference if after if there are instructions in the loop.
Return with continue:
Within a for, while, or do-while loop, a continue statement that does not break the loop like, but returns to the loop head. After evaluation, The next step of the sequential expression is to check whether the loop. A common field of application is Loops that keep fetching and testing values in the hull for so long, until they are suitable for further processing. Here’s an example, again with the guessing game. The user is that it shall only enter numbers between 1 and 5 (inclusive), but if he enters -1234567, it doesn’t matter. We want to change that. by putting forward a test that leads back to the input if the Value range is incorrect. continue helps us get back to the beginning of the Blocks to come and that starts with a new Command Prompt.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class demo{ public static void main(String[] args) { int number = (int) (Math.random() * 5 + 1); while (true) { System.out.println( "What number do I think is between 1 and 5?" ); int guess = new java.util.Scanner(System.in).nextInt(); if ( guess < 1 || guess > 5 ) { System.out.println( "Numbers between 1 and 5 only!" ); continue; } if ( number == guess ) { System.out.println( "Super typed!" ); break; // End of loop } else if ( number > guess ) System.out.println( "Nah, my number is bigger than yours!" ); else if ( number < guess ) System.out.println( "Nah, my number is smaller than yours!" ); } } } |
output:
However, some program pieces are more readable without continuing. On continue at the end of an if query can be performed by an else part be significantly clearer. First, the bad example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
while (condition) { // Shrugged by continue if (Other condition) { // Code,Code,Code continue; } // Another nice code } |
Much clearer is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
while (condition) { if (Other condition) { // code, code, code } else { // Another nice code } } |
java break and continue with label:
Although the keyword goto in the list of reserved words, Java does not allow any jumps, and goto is without functionality. However, Java statements – or a Block that is a special statement – highlight. A reason for Introduction of labels is that break or continue is ambiguous:
- If there are two nested loops, a break in the inner loop only break the inner loop. What is but if the outer loop is to be terminated? The The same applies to continue if the outer loop continues and not the inner one.
- Not only loops use the break keyword, but also the switch statement. What if a loop is a switch statement, but not the local case branch with break, but the whole loop with break should be canceled?
The language designers of Java have decided to labels so that java break and continue the selected statement can either leave or pass through it again. Wrong, they can of course become spaghetti code as from the world of unstructured programming languages. However, as responsible Java programmers we will feature the of course not abuse.
break with a label for loops:
Let’s look at a first example with a label in which break not only out of the inner vicious loop, but out the outer is identical to. label are defined by an identifier is completed with colon and placed in front of a statement the statement is label like a loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
heaven: while (true) { Light: while (true) break /* continue */ heaven // System.out.println( "bright"); } System.out.println( "heaven" ); |
A break without a label in the inner while loop ends only the internal repetition, and a continue would be used to continue this internal while loop. Our example shows the application of a label behind the keywords break and continues. The example does not use the light label and the line with the Output “hell” is deliberately excluded because it is not available and would otherwise cause a compiler error. That the statement is unreachable, is clear because with break heaven the program never comes to the next instruction behind the inner loop, and thus a console output is not reachable. Let’s put a break light in the inner loop instead of break heaven. This will change:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
heaven: while (true) { Light: while (true) break /* continue */ light; System.out.println( "bright"); } // System.out.println( "heaven" ); |
In this scenario, the output”heaven”is not available and must be are commented out. The break bright in the inner loop acts like a simple break without a mark, and the running program continually results in screen output of “hell”.
Get out of the switch case with the break and a label:
Since the break has several functions in the Java language, is ambiguous when the case block of a switch
statement.
In the following example, a loop executes a string. Access to a character in the string realizes the string object method charAt( int ); the length of a string returns length(). As a sign in String should be allowed C, G, A, T. For statistics on the number of of each letter counts a switch statement on the hit the correct variable c, g, a, t by 1. If a character in the string, the loop is terminated. And right here the label gets its appearance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
public class demo{ public static void main(String[] args) { String data = "CGCAGTTCTTCGGXAC"; int a = 0, g = 0, c = 0, t = 0; loop: for ( int i = 0; i < data.length(); i++) { switch ( data.charAt( i ) ) { case 'A': case 'a': a++; break; case 'G': case 'g': g++; break; case 'C': case 'c': c++; break; case 'T': case 't': t++; break; default: System.err.println( "Unknown character " + data.charAt( i ) ); break loop; } } System.out.printf("Count: A=%d, G=%d, C=%d, T=%d%n", a, g, c, t ); } } |
output:
Java break and continue Programming examples:
Example: find the sum of the first 10 positive number:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Scanner; class demo{ public static void main(String[] args) { Double number, sum = 0.0; // create an object of Scanner Scanner input = new Scanner(System.in); for (int i = 1; i < 11; ++i) { System.out.print("Enter number " + i + " : "); // takes input from the user number = input.nextDouble(); // if number is negative // continue statement is executed if (number <= 0.0) { continue; } sum += number; } System.out.println("Sum = " + sum); input.close(); } } |
output:
Example: how to use continue with nested loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class demo{ public static void main(String[] args) { int i = 1, j = 1; // outer loop while (i <= 3) { System.out.println("Outer Loop: " + i); // inner loop while(j <= 3) { if(j == 2) { j++; continue; } System.out.println("Inner Loop: " + j); j++; } i++; } } } |
output:
Example: how to use single continue label in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class demo{ public static void main(String[] args) { // outer loop is labeled as first first: for (int i = 1; i < 6; ++i) { // inner loop for (int j = 1; j < 5; ++j) { if (i == 3 || j == 2) // skips the current iteration of outer loop continue first; System.out.println("i = " + i + "; j = " + j); } } } } |
output:
Example: how to use break label in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class demo{ public static void main(String args[]) { // First label first: for (int i = 0; i < 3; i++) { // Second label second: for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { // Using break statement with label break first; } System.out.println(i + " " + j); } } } } |
output:
Example: how to use multiple continue label in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class demo{ public static void main(String args[]) { // First label first: for (int i = 0; i < 3; i++) { // Second label second: for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { // Using continue statement with label continue first; } System.out.println(i + " " + j); } } } } |
output:
Example: how to use break label and continue label in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class demo{ public static void main(String args[]) { label1: for (int i = 0; i < 3; i++) { for (int j = 0; j< 3; j++){ if(i == 1){ continue label1; } System.out.print(" [i = " + i + ", j = " + j + "] "); } } System.out.println(); label2: for (int i = 0; i < 3; i++) { for (int j = 0; j< 3; j++){ if(i == 1){ break label2; } System.out.print(" [i = " + i + ", j = " + j + "] "); } } } } |
output:
Label1 is the label for first outermost for loop and continue label1 cause the loop to skip print statement if i = 1;
Label2 is the label for second outermost for loop and continue label2 cause the loop to break the loop.
Related Articles:
Java for Loop Statements with Programming Examples
java while loop and java do while loop with programming examples
Java Switch Statement with Programming Examples