break, continue and label in Java loop


Following example showcases labels 'first', 'second' before a for statement and use the break/continue controls to jump to that label. See the example below.

Example

Live Demo

public class Tester {
   public static void main(String args[]) {
      first:
         for (int i = 0; i < 3; i++) {
            for (int j = 0; j< 3; j++){
               if(i == 1){
                  continue first;
               }      
               System.out.print(" [i = " + i + ", j = " + j + "] ");
            }
         }
     
         System.out.println();
     
         second:
            for (int i = 0; i < 3; i++) {
               for (int j = 0; j< 3; j++){
                  if(i == 1){
                     break second;
                  }    
 
                  System.out.print(" [i = " + i + ", j = " + j + "] ");
               }
            }
    }
}

first is the label for first outermost for loop and continue first cause the loop to skip print statement if i = 1;

second is the label for second outermost for loop and continue second cause the loop to break the loop.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 17-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements