pdf of the lecure.
Lesson 9: Break and Continue Keywords
Additional loop control mechanisms in Java programming.
Contents
Laboratory Work
Tasks for Independent Work
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 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:
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:
- Terminates input when a negative number is entered (break).
- 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:
- 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); - Step 2. Variable Declaration
- Create variables for the current input number (number) and a counter for processed numbers (count).
int number; int count = 0; - 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(); - 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; } - 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; } - Step 6. Output Odd Numbers
- If the number is odd (and not negative), output it.
System.out.println("Odd number: " + number); } - Step 7. Final Output After Loop Completion
- Show how many numbers were processed before termination.
System.out.println("Total numbers processed: " + count); scanner.close(); } } - Run the program (e.g., press F5 in your IDE).
- Test with different values to see the output.
- 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:
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:
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:
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:
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