Java

  1. Home
  2. Computing & Technology
  3. Java
photo of Paul Leahy

Paul's Java Blog

By Paul Leahy, About.com Guide to Java

Monday's Programming Question

Monday January 12, 2009

Today the programming question is a simple one about jumping out of loops. I think for the most part 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?

Comments

January 13, 2009 at 10:12 am
(1) Njoroge says:

The first break, resumes after the if statement it is enclosed in, while the labeled break, breaks from loop1, to resume on the println method, thus an output of 67-5 = 62.

January 20, 2009 at 4:50 am
(2) Paul Leahy says:

You were almost right. The first break statement jumps out of the for loop completely, not just the if statement. See the answer post for full details.

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Discuss

Community Forum

Explore Java

About.com Special Features

Java

  1. Home
  2. Computing & Technology
  3. Java

©2009 About.com, a part of The New York Times Company.

All rights reserved.