1. Computing

Breaking Out

By

Level: Beginner

Focus: Loops, Break Statement

Breaking Out Question

The focus of this programming question is on jumping out of loops. Almost always it's possible to write loops without the need for a break statement but sometimes it's convenient to do so. The following program does not contain examples of well written loops or ones that need a break statement. It's purpose is to get you thinking about how the break statement changes the logical flow of the code:

 public class BreakingLoop {
 
   public static void main(String[] args) {
 
     int count = 0; 
     loop_one:
     for (int k=5;k < 100;k++)
     {
       for (int j=3; j < 100; j++)
       {
         if (j % 2 == 0)
         {
           break;
         }
         if (k == 67)
         {
           break loop_one;
         }
         count ++;
       }
     }
     System.out.println(count);
   }
 }
 

There are two break statements in the program, one with a label and one without. The question is for each break statement what is the next line to be executed and what is the final total of the variable count?

To get the most out of this question try and figure out the answer before coming back to read the solution on the next page.

  1. About.com
  2. Computing
  3. Java
  4. Programming Exercises
  5. Beginner Level
  6. Breaking Out

©2014 About.com. All rights reserved.