dcsimg
December 14, 2017
Hot Topics:

Understanding the Java Labeled Statement

  • September 25, 2017
  • By Manoj Debnath
  • Send Email »
  • More Articles »

Java provides a feature not very frequently used, called the labeled statement. This feature is somewhat reminiscent of assembly language programming in the sense that we can create a labeled block of code and refer to the label when transferring program control to the end or beginning of the labeled statement with the keywords break and continue, respectively. This article describes this feature and shows how to use them with appropriate examples.

Overview

A program generally is a linear flow of execution of consecutive statements. The programmer imposes certain controls to redirect the flow in an appropriate direction based upon some logic. There are different ways to control the flow of a program in Java. The statements written using those keywords are called control statements. Java's break and continue statements belong to that genre and helps in alternating the flow of the program. These two keywords can be used in association with a label or without a label. We mostly use them without a label, but they also may be used with a label. With a brief overview of these two control statements, we'll delve into its labeled part down the line.

The break Statement, Without a Label

The common usage of break statements is that we generally use them to terminate a switch statement in execution. It exits from the block to execute the next statement after the block.

package org.mano.example;

public class SwitchCaseDemo {

   public static void main(String[] args) {
      String emote = "happy";
      String emoticon = "/-s";
      switch (emote) {
         case "happy":
            emoticon = ":-)";
            break;
         case "sad":
            emoticon = ":-(";
            break;
         case "playful":
            emoticon = ";)";
            break;
         case "angry":
            emoticon = ">:(";
            break;
         case "embarassed":
            emoticon = ":-/";
            break;
         case "shocked":
            emoticon = ":-o";
            break;
         default:
            emoticon = ":-?";
            break;
      }
      System.out.println(emoticon);

   }

}

In the switch statement, the break in each case indicates that the processing should terminate after processing the case. However, the break statement is not required for the last case depicted here as the optional default case because the execution continues with the next statement after the switch. The default case is generally the last statement in the switch block. However, there is no such strict rule. As a result, the default case may be put anywhere in the order of cases and thereby accompanies the break statement.

With repetitive statement like loops, break statements causes immediate exits from the cycle. This is especially done to have an early escape from the loop or to skip remaining statements. The execution, however, continues with the first statement after the control statement. Here is an example:

package org.mano.example;

public class LoopBreakDemo {

   public static void main(String[] args) {

      int i = 0;

      for (i = 9999; i <= 99999; i++) {
         if (i % 397 == 0)
         break;
      }
      System.out.println("First number "
         + "divisible by 397 between "
         + "9999 and 99999 is = " + i);
   }
}

When the if statement within the for loop detects the i % 397 == 0, the break statement executes. It terminates the loop and execute the System.out.println(...) statement because it is the next statement after the execution of break statement.

The break Statement, with a Label

Sometimes, it is a requirement of the program logic to exit from the entire nested control statement with just one statement rather than wait for it to complete the entire execution. This type of situation is particularly suitable for a labeled break statement. This statement enables one to break from the entire labeled block in one go. The program execution resumes from the first statement encountered after the enclosing labeled break statement. Let's write a couple of simple programs, one with labeled break and one with a simple break, and observe the difference in output.

Here is a program with a simple break statement:

package org.mano.example;

public class SimpleBreakDemo {

   public static void main(String[] args) {

      int counter = 0;
      for (int i = 0; i <= 10; i++) {
         for (int j = 0; j <= 10; j++) {
            if (i == 5)
               break;
            }
            counter++;
         }
      System.out.println(counter);
   }
}

Output: 11

Here is a program with a labeled break statement:

package org.mano.example;

public class LabeledBreakDemo {

   public static void main(String[] args) {
      int counter = 0;
      start: {
         for (int i = 0; i <= 10; i++) {
            for (int j = 0; j <= 10; j++) {
               if (i == 5)
                  break start;
            }
            counter++;
         }
      }
      System.out.println(counter);
   }
>}

Output: 5

Observe that, in the second program, there is a labeled block, called start:, and the nested for-loops are enclosed within the block. When the labeled break statement is executed, it skips all the remaining operations from that point to the end of the enclosing labeled block and resumes execution thereafter. Therefore, the labeled break statement is a flexible way to define the usual length of the jump by using the unlabelled break statements.

The continue Statement, Without a Label

The continue statement, when used in association with loops in Java, skips the remaining statements in the loop body and proceeds to the next iteration of the loop. This is in contrast to the break statements, where it escapes from the immediate loop. The continue statement simple resumes the loop beginning with the next iteration.

package  org.mano.example;

public class SimpleContinueDemo {

   public static void main(String[] args) {
      String[] listOfNames = { "Ravi", "Soma",
         "null", "Colin", "Harry", "null",
         "Smith" };

      for (int i = 0; i < listOfNames.length; i++) {
         if (listOfNames[i].equals("null"))
            continue;
         System.out.println(listOfNames[i]);
      }
   }
}

Output:

Ravi
Soma
Colin
Harry
Smith

Observe how the continue statement skipped the names from the list that contained "null" as a string value.

The continue Statement, with a Label

The labeled continue statement is similar to the unlabelled continue statement in the sense that both resume the iteration. The difference with the labeled continue statement is that it resumes operation from the target label defined in the code. As soon as the labeled continue is encountered, it skips the remaining statements from the statement's body and any number of enclosing loops and jumps to the nest iteration of the enclosing labeled loop statements. Here is an example to illustrate the labeled continue statement.

package org.mano.example;

public class LabeledContinueDemo {

   public static void main(String[] args) {

      start: for (int i = 0; i < 5; i++) {
         System.out.println();
         for (int j = 0; j < 10; j++) {
            System.out.print("#");
            if (j >= i)
               continue start;
         }
         System.out.println("This will never"
            + " be printed");
      }
   }
}

The for loop has been started with a label. When the continue statement is executed, it jumps to the target label start: and begins the iteration afresh. And, other statements after the continue operation are simply skipped. This is the reason the third System.out.println(...) will never get a chance to execute.

Conclusion

The labeled break and continue statements are the only way to write statements similar to goto. Java does not support goto statements. It is good programming practice to use fewer or no break and continue statements in program code to leverage readability. It is almost always possible to design program logic in a manner never to use break and continue statements. Too many labels of nested controls can be difficult to read. Therefore, it is always better to avoid such code unless there is no other way.






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date