Explain Codes LogoExplain Codes Logo

Difference between break and continue statement

java
loop-control
best-practices
programming-principles
Alex KataevbyAlex Kataev·Sep 11, 2024
TLDR

The break is the abrupt exit artist; it leaves the loop or switch statement just like that - no questions asked!

break in action:

for (int i = 0; i < 3; i++) { if (i == 1) break; // Excuse me, I must go, my planet needs me! System.out.print(i + " "); // Output: 0 }

In contrast, the continue is the smooth operator; it proceeds to the next iteration by skillfully stepping over the rest of the current one.

continue demonstrated:

for (int i = 0; i < 3; i++) { if (i == 1) continue; // Relax! Just a step over the current one, not the moon! System.out.print(i + " "); // Output: 0 2 }

break bails; continue jumps the line.

Loop control Principles

break and continue are the essential gear shifters for a smooth ride in a loop.

Clever ways to use break and continue

  • Use break as the exit door when you reach the end of the loop's usefulness.
  • Pull out the continue statement to leap over parts of the iteration that are unnecessary or uninteresting.

Wise practices and cautions

  • Excessive use of break can lead to knots in the code's control flow, making it harder to follow.
  • Labels help with control flow in nested loops, but they can also turn your code into a maze.
  • Avoid labelled blocks where possible for simplicity's sake.
  • If labels are your thing, make sure you honor proper naming conventions to steer clear of confusion.

Loop control masterclass

Maximizing Efficiency with break

Oil your loop machinery with break and see the magic:

  • In a search algorithm, put on the brakes once the item is found.
  • When your loop is stuck in an existential crisis 😱 (infinite loop), use break to snap it back to reality.

Nifty uses of continue

Make your loops jump hoops with continue:

  • When dealing with data, it helps filter out the noise.
  • During a loop iteration, continue says, "I see your exceptional condition and I raise you a skip!"

Practical Applications: Unleashing the potential

break:

// Find first divisible number by 91 and break out of loop for (int i = 1; i <= 1000; i++) { if (i % 91 == 0) { System.out.println("First divisible by 91: " + i); break; // And I... am... Iron Man! *Snap* } }

continue:

// Print non-prime numbers between 1 and 10 for (int i = 2; i <= 10; i++) { for (int j = 2; j < i; j++) { if (i % j == 0) { System.out.println(i); // I'm naughty non-prime! Ha-ha! break; } } }

Mastering these loop controls empowers you to write better, efficient code while having some fun along the way!