Skip to main content
Published on

break and continue in Java

Share:

Introduction

break and continue are fundamental keywords in Java, used to control the flow of loops such as for, while, and do-while. These keywords provide more refined control over loop behaviour in specific situations.

The break

break is used to immediately terminate the loop it is in. It is commonly used in loops and switch statements. When used inside a loop:

  • The loop is terminated immediately.
  • Program control jumps to the first line after the loop block.

The continue

continue, on the other hand, skips the rest of the code in the current iteration and advances to the next iteration. When using continue:

  • The current iteration ends prematurely.
  • The loop is not abandoned, but continues with the next iteration.

Practical Example

Here is an illustrative example showing the use of break and continue:

package com.caffeinealgorithm.programaremjava;

import java.util.ArrayList;
import java.util.List;

public class BreakAndContinue {
  public void Run() {
    List<String> animals = new ArrayList<>();
    int counter = 0;

    animals.add("Dog");
    animals.add("Cat");
    animals.add("Chicken");
    animals.add("Rabbit");
    animals.add("Lion");

    for (String animal : animals) {
      System.out.printf("Animal: %s\n", animal);

      if (animal == "Chicken")
        break;
    }

    while (counter < 10) {
      counter++;

      if (counter == 5)
        continue;

      System.out.printf("Counter: %d\n", counter);
    }
  }
}

/*
  Animal: Dog
  Animal: Cat
  Animal: Chicken
  Counter: 1
  Counter: 2
  Counter: 3
  Counter: 4
  Counter: 6
  Counter: 7
  Counter: 8
  Counter: 9
  Counter: 10
*/

Example Analysis

In the example:

  • break is used to stop the loop as soon as the animal "Chicken" is found.
  • continue is used to skip the print when the counter equals 5.

Applications and Best Practices

  • break in Nested Loops: In nested loops, break will only terminate the loop it is currently in.
  • Avoiding Excessive break and continue: Overuse can make the code confusing. It is important to keep the code clear and readable.
  • continue in Complex Conditions: Useful when there are multiple conditions that require skipping an iteration.

Warnings

  • Code Readability: The use of these keywords can make the program flow less obvious, especially for beginners.
  • Debugging: It can be harder to debug loops with multiple break or continue statements.

Conclusion

break and continue are powerful tools in Java, but they should be used with care. Understanding their uses and limitations is crucial for writing efficient and maintainable code.

Happy coding!