Break and Continue
BREAK KEYWORD
Definition
The break keyword is used to terminate the execution of a loop prematurely.
When break is encountered inside a loop (for, while, or do-while), it immediately exits the loop.
Syntax
Basic syntax of break in a loop:
for (initialization; condition; increment) { // Loop body if (someCondition) { break; // Terminate the loop if the condition is met } }
Example Code
Example using break in a for loop:
public class BreakExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println(i); if (i == 3) { System.out.println("Breaking the loop at i = 3"); break; } } } }
OUTPUT
To display numbers 1 to 5.
Termination when i equals 3:
Output:
Breaking the loop at i = 3
Process finished with exit code 0
SQUARE CALCULATION USING BREAK
Without Break Example Code
Code to print squares of numbers from 1 to 5:
public class SquareCalc { public void printSquared() { int number = 1; while (number <= 5) { int square = number * number; System.out.println("Square of " + number + ":" + square); number++; } } public static void main(String[] args) { SquareCalc sq = new SquareCalc(); sq.printSquared(); } }
OUTPUT
Square of 1: 1
Square of 2: 4
Square of 3: 9
Square of 4: 16
Square of 5: 25
Process finished with exit code 0
With Break Example Code
Modified code to use break:
public class SquareCalc { public void printSquared() { int number = 1; while (number <= 5) { int square = number * number; System.out.println("Square of " + number + ":" + square); if (number == 3) { System.out.println("Breaking the Loop at number = 3"); break; } number++; } } public static void main(String[] args) { SquareCalc sq = new SquareCalc(); sq.printSquared(); } }
OUTPUT
Square of 1: 1
Square of 2: 4
Square of 3: 9
Breaking the Loop at number = 3
Process finished with exit code 0
CONTINUE KEYWORD
Definition
The continue keyword is used to skip the rest of the code inside a loop for the current iteration and move on to the next iteration.
Example Code
Example using continue in a for loop:
public class ContinueExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { if (i == 3) { System.out.println("Skipping iteration at i = 3"); continue; } System.out.println(i); } } }
OUTPUT
Displaying numbers skipping i = 3:
Output:
1
2
Skipping iteration at i = 3
4
5
Process finished with exit code 0
Square Calculation with Continue
Code example using continue in square calculation:
public class SquareCalc { public void printSquared() { int number = 1; while (number <= 5) { if (number == 3) { System.out.println("Skipping iteration at number = 3"); number++; continue; } int square = number * number; System.out.println("Square of " + number + ": " + square); number++; } } public static void main(String[] args) { SquareCalc sq = new SquareCalc(); sq.printSquared(); } }
OUTPUT
Square of 1: 1
Square of 2: 4
Skipping iteration at number = 3
Square of 4: 16
Square of 5: 25
Process finished with exit code 0