Friday, July 30, 2021

How to Use Break, Continue, and Label in Loop in Java? Example

break and continue in Java are two essential keyword beginners needs to familiar while using loops ( for loop, while loop and do while loop). break statement in java is used to break the loop and transfers control to the line immediately outside of the loop while continue is used to escape current execution and transfers control back to the start of the loop. Both break and continue allows programmers to create sophisticated algorithms and looping constructs.

In this java tutorial, we will see examples of break and continue statements in Java and some important points related to breaking the loop using label and break statements. break keyword can also be used inside switch statements to break current choice and if not used it can cause fall-through on switch. 

Well break is not alone on breaking switch case you can also sued throw keyword on switch case.

This Java tutorial is next in series of articles in looping like 4 ways to loop Map in Java and How to loop on ArrayList in Java. If you are new here and haven’t gone through those articles then you may find them useful.



break and continue statement in Java - example.

break and continue example in java  for loopIn this example we are calculating sum of odd numbers until number 5 appear, where we break the loop by using break statement. after calculating sum we also call continue which cause last line of loop to not execute. remember call to continue is inside if block which checks for odd numbers, so that line will appear in case of even number but not in case of odd number. 

This example of break and continue shows that upon calling break, loop terminates and control goes to first line outside the loop while upon calling continue, loop doesn't terminate but rest of execution doesn't happen and loop continues from next iteration.




/**
 * Simple Java program which demonstrate use of break and continue statements in Java
 * In this example break is used to break loop and continue is used to escape current  *iteration of loop once a condition is true.
 * @author
 */

public class BreakContinueExample {
 
    public static void main(String args[]) {
   
        int[] numbers= new int[]{1,2,3,4,5,6,7,8,9,10};
     
        //calculate sum of all numbers till 5 appears
        int sum = 0;
        for(int i=0; i< numbers.length; i++){
            System.out.println("Executing for loop with iteration number: " + i);
            if(i == 5){
                System.out.println("calling break statement to break for loop");
                break;
            }
            if(i%2 != 0){
                sum = sum + i;
                System.out.println("calling continue statement to start new iteration");
                continue;
            }
            System.out.println("Last line of loop, not executing for odd numbers due
                               to continue statement i: "
+ i);
        }
        System.out.println("Outside of for loop, sum: " + sum);
    }
}

Output:
Executing for loop with iteration number: 0
Last line of loop, not executing for odd numbers due to continue statement i: 0
Executing for loop with iteration number: 1
calling continue statement to start new iteration
Executing for loop with iteration number: 2
Last line of loop, not executing for odd numbers due to continue statement i: 2
Executing for loop with iteration number: 3
calling continue statement to start new iteration
Executing for loop with iteration number: 4
Last line of loop, not executing for odd numbers due to continue statement i: 4
Executing for loop with iteration number: 5
calling break statement to break for loop
Outside of for loop, sum: 4


continue and break examples with label in Java

You can use labels with break and continue. labels are where you can shift control from break and continue. by default break goes outside of loop but if you more than one loop you can use the break statement to break a specific loop by providing labels. 

The same is true for continue. if you are working on nested loops labels gives more control to break and continue. In the following the example of break and continue with labels. we have a nested loop and we have created two labels OUTER and INNER. 

OUTER label is for outer loop and INNER label is for inner loop. we are iterating through array and print value of odd number from outer loop and then use continue statement, which ignores execution of inner loop. if its even number than inner loop executes and breaks as soon as it prints the number.

/**
 * Simple Java program which demonstrate use of break and continue statements in Java
 * with lables, break and continue can be used alongside label and loop.
 *
 * @author Javin
 */

public class BreakContinueWithLabel {
 
    public static void main(String args[]) {
   
        int[] numbers= new int[]{100,18,21,30};
     
        //Outer loop checks if number is multiple of 2
        OUTER:  //outer label
        for(int i = 0; i<numbers.length; i++){
            if(i % 2 == 0){
                System.out.println("Odd number: " + i + ", continue from OUTER label");
                continue OUTER;
            }
         
            INNER:
            for(int j = 0; j<numbers.length; j++){
                System.out.println("Even number: " + i + ", break  from INNER label");
                break INNER;
            }
        }
     
    }
}

Output:
Odd number: 0, continue from OUTER label
Even number: 1, break  from INNER label
Odd number: 2, continue from OUTER label
Even number: 3, break  from INNER label


As shown in the above example of break and continue with labels, It provides a lot of conveniences to break and continue in case of a nested loop.

Important point about the break and continue in Java

1. break keyword transfers control to next statement outside loop while continue keyword transfers control to the beginning of loop, ignoring rest of lines in loop.

2. break can also be used inside CASE statement of switch construct.
3. an optional label can be provided after break and continue which cause to apply break and continue on specified loop.

That's all on break and continue statement in Java. break and continue allows programmer to control flow of execution in loops. We have also seen example of break and continue with and without labels , which allows you to write more sophisticated looping construct in java.


Other Java beginners tutorial you may like

12 comments :

Jirka Pinkas said...

Another important thing about labels is that you shouldn't use them if you don't have to. I don't use them at all many years. Why not use them? Because they make logic of your code much less readable.

tommy said...

I never heard from "label" before. thnx for your interesting article about it. But it sounds a lot like "goto" in other programming languages. IMHO this construct should be avoided cause it complicates the code. Do you agree?

Anonymous said...

Here is another tricky question on switch and break. The question checks to see if the person is clear on the break statement or not
public class SwitchDemo {
public static void main(String[] args) {

int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
System.out.println("August " + monthString);
//break;
case 9: monthString = "September";
System.out.println("September " + monthString);
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}

Unknown said...

You are not actually using the numbers[] array, you are performing checks on the index.

Unknown said...

Also, in the last example, the code without the labels produces exactly the same output as the code with labels.

Anonymous said...

When i % 2 == 0, i is even, not odd.

Anonymous said...

here in sysout statements odd number and even number are mistakenly written, isn' t it?

Anonymous said...

Actually your loop doesn't make anything with int[]numbers - it's using it only to check lenght for loop. Here's my updated version:

int[] numbers = new int[] { 100, 18, 21, 30 };

OUTER: for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
System.out.println("Loop at " + i + " Odd number: "
+ numbers[i] + ", continue from OUTER label");
continue OUTER;
}

INNER: for (int j = 0; j < numbers.length; j++) {
if (numbers[j] % 2 == 1) {
System.out.println("Loop at " + j + " Even number: "
+ numbers[j] + ", break from INNER label");
break INNER;
}
}
}

Unknown said...

can i break INNER; from OUTER
and break OUTER; from INNER

Unknown said...

Cool Example but the Even and Odd Section is inverted 1%2 equal 1 which is odd not even considering the mentioned logic...

Unknown said...

can we use label break outside a loop?

Unknown said...

What had you done? Why did you use the array? And are odd numbers divisible by 2?

Dont show oversmartness because some beginner, who are willing to understand would understand nothing..

Post a Comment