Sitemap

Difference between break & continue statements in Java?

2 min readAug 25, 2024

--

In Java, both break and continue are control flow statements that alter the normal flow of loops such as for, while, and do-while. They are used to control the execution of the loop in different ways.

break Statement

The break statement is used to terminate the loop entirely. When break is encountered, the control exits the loop immediately, and the program continues with the next statement following the loop.

continue Statement

The continue statement is used to skip the current iteration of the loop and proceed with the next iteration. It does not terminate the loop; instead, it bypasses the remaining code in the current iteration and jumps to the loop's next iteration.

Differences between break and continue

break:

  • Exits the loop entirely.
  • The loop is terminated as soon as break is encountered.
  • Often used in switch statements and loops.

continue:

  • Skips the current iteration and moves to the next iteration.
  • The loop continues to execute after the continue statement.
  • Useful when you want to skip certain conditions in a loop.

Example of break

Press enter or click to view image in full size

Get Amarjeet Kumar Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

output below:

Press enter or click to view image in full size

Explanation:

  • The loop runs from 1 to 10.
  • When i equals 5, the break statement is executed, which immediately exits the loop.
  • The subsequent numbers (5 to 10) are not printed because the loop is terminated.

Example of Continue

Press enter or click to view image in full size

output below:

Press enter or click to view image in full size

Explanation:

  • The loop runs from 1 to 10.
  • When i equals 5, the continue statement is executed, which skips the rest of the loop body for that iteration.
  • The number 5 is not printed, but the loop continues with the next iteration.

Summary

  • Use break when you want to exit the loop completely based on a certain condition.
  • Use continue when you want to skip the current iteration of the loop and proceed with the next one.

These statements give you more control over how loops execute in Java, allowing you to handle specific conditions more effectively.

--

--

Amarjeet Kumar Singh
Amarjeet Kumar Singh

Written by Amarjeet Kumar Singh

Experienced Java Full Stack Developer, Java Trainer, and Freelancer, Explore my work and Join our Publications:👉 https://medium.com/@amarjeetcs79