How to use labels in Java code?

Java 8Object Oriented ProgrammingProgramming

Java provides two types of branching/control statements namely, break and continue.

The break statement

This statement terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

Example

Following is the example of the break statement. Here we are trying to print elements up to 10 and, using break statement we are terminating the loop when the value in the loop reaches 8.

Live Demo

public class BreakExample {
   public static void main(String args[]){
      for(int i=0; i<10; i++){
         if (i==8){
            break;
         }
         System.out.println("......."+i);
      }
   }
}

Output

.......0
.......1
.......2
.......3
.......4
.......5
.......6
.......7

The continue statement

 This statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Example

Following is the example of the continue statement. Here we are trying to print elements up to 10 and, using break continue we are skipping the loop when the value in the loop reaches 8.

Live Demo

public class ContinueExample {
   public static void main(String args[]){
      for(int i=0; i<10; i++){
         if (i==8){
            continue;
         }
         System.out.println("......."+i);
      }
   }
}

Output

.......0
.......1
.......2
.......3
.......4
.......5
.......6
.......7
.......9

Java provides two types of branching statements namely, labelled and unlabelled.

We can also use the above-mentioned branching statements with labels.

You can assign a label to the break/continue statement and can use that label with the break/continue statement as −

Task:
for(int i=0; i<10; i++){
   if (i==8){
      continue Task;
      (or)
      break Task;
   }
}

The labelled break statement

The labeled break statement terminates the outer most loop whereas the normal break statement terminates the innermost loop.

Example

Live Demo

public class LabeledBreakExample {
   public static void main(String args[]){
      Task:
      for(int i=0; i<10; i++){
         if (i==8){
            break Task;
          }
          System.out.println("......."+i );
      }
   }
}

Output:

.......0
.......1
.......2
.......3
.......4
.......5
.......6
.......7
.......9

The labelled continue statement

The labelled continue statement skips the current iteration of the outer most loop whereas the normal continue skips the current iteration of the innermost loop.

Example

Live Demo

public class LabeledContinueExample {
   public static void main(String args[]){
      Task:
      for(int i=0; i<10; i++){
          if (i==8){
             continue Task;
          }
          System.out.println("......."+i );
       }  
   }  
}

Output

.......0
.......1
.......2
.......3
.......4
.......5
.......6
.......7
.......9
raja
Published on 05-Jan-2018 07:54:21
Advertisements