Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Java Programming Language (Eng)

  1. Home
  2. Courses
  3. Весенний семестр
  4. Java Eng
  5. Basic Programming Language Constructs
  6. Lesson #9: Break and Continue

Lesson #9: Break and Continue

pdf of the lecure.

Lesson 9: Break and Continue Keywords

Additional loop control mechanisms in Java programming.

Contents

Laboratory Work

  • • Lab 1: Break and Continue

Tasks for Independent Work

  • • Task 1: Break - Stop at 7
  • • Task 2: Continue - Skip Multiples of 3
  • • Task 3: Break and Continue - Complex Conditions
  • • Task 4: Break and Continue with Strings
  • • Task 5: Rewrite TestBreak and TestContinue

Introduction to Break and Continue

Important: The break and continue keywords provide additional loop control mechanisms. These keywords can simplify programming in some cases, but excessive or improper use can make programs harder to read and debug.

The Break Keyword

The break keyword can be used to immediately terminate a loop. The TestBreak program demonstrates the result of using break in a while loop. This program calculates the sum of integers from 1 to 20 until the sum is greater than or equal to 100:

public class TestBreak {
  public static void main(String[] args) {
    int sum, number;

    sum = 0;
    number = 0;
    while (number < 20) {
      number++;
      sum += number;
      if (sum >= 100) 
        break;
    }
    System.out.println("The number is " + number);
    System.out.println("The sum is " + sum);
  }
}

Without the if statement, the program would simply calculate the sum of numbers from 1 to 20. However, with the if statement, the loop terminates when the sum becomes greater than or equal to 100. Without the if statement, the output would be:

The number is 20
The sum is 210

The Continue Keyword

The continue keyword can also be used in loops. When continue is encountered in a loop, the current iteration ends, and control transfers to the end of the loop body. In other words, continue breaks the current loop iteration, while break breaks the entire loop.

The TestContinue program demonstrates the results of using continue in a while loop. This program sums integers from 1 to 20, excluding 10 and 11:

public class TestContinue {
  public static void main(String[] args) {
    int sum, number;
    
    sum = 0;
    number = 0;
    while (number < 20) {
      number++;
      if (number == 10 || number == 11) 
        continue;
      sum += number;
    }
    System.out.println("The sum is " + sum);
  }
}

Using the if statement, the continue statement is executed if number becomes equal to 10 or 11. The continue statement ends the current iteration, so the remaining part of the loop body is not executed; therefore, number is not added to the sum when it equals 10 or 11. Without the if statement, the output would be:

The sum is 210

In this case, all numbers are summed, even when number equals 10 or 11, so the result is 210, which is 21 more than it would be with the if statement.

Important: The continue statement is always inside a loop body. In while and do-while loops, the loop repetition condition is evaluated immediately after the continue statement. In a for loop, the loop control variable is updated first, then, immediately after continue, the loop repetition condition is evaluated.

When to Use Break and Continue

You can always write a program without using break or continue in loops. In general, it's advisable to use break and continue only if they simplify coding and make programs easier to read.

Suppose you need to write a program that finds the smallest divisor other than 1 for an integer n (let n >= 2). Using the break statement, you can write simple and intuitive code as follows:

int factor = 2;
while (factor <= n) {
  if (n % factor == 0)
    break;
  factor++;
}
System.out.println("The smallest divisor other than 1 for "
  + n + " is " + factor);

This code can be rewritten without using break as follows:

boolean found = false;
int factor = 2;
while (factor <= n && !found) {
  if (n % factor == 0)
    found = true;
  else
    factor++;
}
System.out.println("The smallest divisor other than 1 for "
  + n + " is " + factor);

Obviously, in this case, break simplifies this program and makes it easier to read. However, break and continue should be used with caution. Too many break and continue statements create loops with multiple exit points and make programs difficult to read.

Laboratory Work

Lab 1: Break and Continue

Objective: Write a program that analyzes a sequence of numbers entered by the user and performs two actions:

  1. Terminates input when a negative number is entered (break).
  2. Skips even numbers when outputting (continue).

Expected Output:

Enter numbers (negative number ends input):
Number 1: 5
Odd number: 5
Number 2: 8
8 — even, skipping.
Number 3: 3
Odd number: 3
Number 4: -1
Negative number entered. Ending input.
Total numbers processed: 3

File Name: L9Lab1.java
Class Name: L9Lab1

Algorithm:

  1. Step 1. Environment Preparation and Class Import
    • Create a new Java file named L9Lab1.java.
    • Import the Scanner class for input.
    import java.util.Scanner; public class L9Lab1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
  2. Step 2. Variable Declaration
    • Create variables for the current input number (number) and a counter for processed numbers (count).
    int number; int count = 0;
  3. Step 3. Organizing an Infinite Loop with while
    • Use while (true) to continue the loop until explicitly terminated with break.
    System.out.println("Enter numbers (negative number ends input):"); while (true) { System.out.print("Number " + (count + 1) + ": "); number = scanner.nextInt();
  4. Step 4. Checking for Negative Number (break)
    • If a negative number is entered, display a message and break the loop.
    if (number < 0) { System.out.println("Negative number entered. Ending input."); break; }
  5. Step 5. Increment Counter and Check for Even Numbers (continue)
    • Increment the counter. If the number is even, skip further processing using continue.
    count++; if (number % 2 == 0) { System.out.println(number + " — even, skipping."); continue; }
  6. Step 6. Output Odd Numbers
    • If the number is odd (and not negative), output it.
    System.out.println("Odd number: " + number); }
  7. Step 7. Final Output After Loop Completion
    • Show how many numbers were processed before termination.
    System.out.println("Total numbers processed: " + count); scanner.close(); } }
  8. Run the program (e.g., press F5 in your IDE).
  9. Test with different values to see the output.
  10. Upload the file to the learning management system.

Tasks for Independent Work

Task 1: Break - Stop at 7

To do: Output numbers from 1 to 10, but break the loop as soon as the number 7 is encountered.

Expected Output:

1
2
3
4
5
6

File Name: L9Task1.java

Task 2: Continue - Skip Multiples of 3

To do: Output all numbers from 1 to 15, except numbers divisible by 3 (use continue).

Expected Output:

1
2
4
5
7
8
10
11
13
14

File Name: L9Task2.java

Task 3: Break and Continue - Complex Conditions

To do: Output numbers from 1 to 20, but skip numbers ending in 5, and break the loop at number 17.

Expected Output:

1
2
3
4
6
7
8
9
11
12
13
14
16

File Name: L9Task3.java

Task 4: Break and Continue with Strings

To do: Traverse a string character by character. Output only letters (skip digits and special characters). If the character '!' is encountered, break the loop.

Expected Output:

Enter text
Hello123!World
Result:
H
e
l
l
o

File Name: L9Task4.java

Task 5: Rewrite TestBreak and TestContinue

To do: Rewrite the TestBreak and TestContinue programs without using break and continue.

TestBreak: The TestBreak program calculates the sum of integers from 1 to 20 until the sum is greater than or equal to 100.

TestContinue: The program sums integers from 1 to 20, excluding 10 and 11.

File Name: L9Task5.java

© Educational Platform for Students. Lesson 9: Break and Continue Keywords.

Решения: Lab1 import java.util.Scanner; public class BreakContinueLab { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number; int count = 0; System.out.println("Введите числа (отрицательное число завершит ввод):"); while (true) { System.out.print("Число " + (count + 1) + ": "); number = scanner.nextInt(); if (number < 0) { System.out.println("Введено отрицательное число. Завершение ввода."); break; } count++; if (number % 2 == 0) { System.out.println(number + " — чётное, пропускаем."); continue; } System.out.println("Нечётное число: " + number); } System.out.println("Всего обработано чисел: " + count); scanner.close(); } } ________________________________________ Task 1 java for (int i = 1; i <= 10; i++) { if (i == 7) { break; } System.out.println(i); } Task 2 Вывести все числа от 1 до 15, кроме чисел, кратных 3 (использовать continue). java for (int i = 1; i <= 15; i++) { if (i % 3 == 0) { continue; } System.out.println(i); } Task 3. Вывести числа от 1 до 20, но пропустить числа, оканчивающиеся на 5, и прервать цикл на числе 17. java for (int i = 1; i <= 20; i++) { if (i == 17) { break; } if (i % 10 == 5) { continue; } System.out.println(i); } Task 4. Пройти по строке символ за символом. Выводить только буквы (пропустить цифры и спецсимволы). Если встретится символ '!' — прервать цикл. String str = "Hello123!World"; for (char c : str.toCharArray()) { if (c == '!') { break; } if (Character.isLetter(c)) { System.out.println(c); } }
◄ Lesson 8: While Loops
Lesson # 10: Methods ►
Skip Navigation
Navigation
  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • ТФНД

        • МО_4курс

        • KP

        • АБМ1_ИИБ_25-26

        • Java Eng

          • Lesson 0. Introduction

          • Basic Programming Language Constructs

            • AssignmentLesson 1. Programming on Java in Microsoft Visual ...

            • AssignmentLesson 2. Data Types and Type Casting. Boolean type

            • AssignmentLesson 3. Java Conditional statement IF

            • AssignmentLesson 4: Ternary Operator and Switch Statement

            • AssignmentLesson #5: Mathematical Functions in Java

            • AssignmentLesson #6: Characters and Strings in Java

            • AssignmentLesson # 7: For and Foreach

            • AssignmentLesson 8: While Loops

            • AssignmentLesson #9: Break and Continue

          • Methods (functions)

          • Arrays

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

          • Topic 11

          • Topic 12

          • Topic 13

          • Topic 14

          • Topic 15

          • Topic 16

        • МО (ПО)

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ

          • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2026

          • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

You are currently using guest access (Log in)
Java Eng
Data retention summary
Get the mobile app Яндекс.Метрика