Explain Codes LogoExplain Codes Logo

What is the "continue" keyword and how does it work in Java?

java
continue
best-practices
nested-loops
Alex KataevbyAlex Kataev·Aug 12, 2024
TLDR

When the continue statement is executed in a loop, it drops everything following it in the loop's body and leaps straight to the next iteration. It's like a trapdoor in your loop! Here's a glimpse of this magic:

Example:

for (int i = 1; i <= 5; i++) { if (i % 2 == 0) continue; // Skip the even ones, they're too "normal" for us System.out.println(i); // Prints the rebellious odd numbers: 1, 3, 5 }

In this case, continue enabled us to print only the odd numbers by completely ignoring the even ones. Such outright bias in a loop, right?

In-depth dissection of "continue"

Mastering precision with continue in loop controls

The continue keyword gives you a finely-tuned power to control the maneuverings within a loop. It empowers you to side-step the additional code within a loop for specific iterations. This means no unnecessary code runs, leaning towards increased efficiency and cleaner code.

The differencer: continue vs break

Comparing continue and break side by side illuminates their different roles. A break is a full stop sign that halts the loop and exits right there. The continue, however, merely skips the rest of the cycle and leaps to the next iteration, leaving the loop still in action.

Wise usage: best practices and warnings

Going overboard with continue may lead to a complex logic labyrinth. Consequently, use it sparingly and refactor if you notice a frequent dependency on it. Much like "hidden GOTOs", cautious and explicit use of continue, break, and return can help maintain clear and understandable loops.

Taking over nested loops with labeled continue

In nested loops, labels combined with continue can stage a coup and control the loop from the outside. A labeled continue jumps straight to the next iteration of the outer labeled loop. It's like having a cube-shaped loop, and continue helps you hop across layers!

How continue works in real world scenarios

Let's check out some Java-flavored snacks here, showing how continue could be used to neatly drive through a nested loop:

outerLoop: for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (array[i][j] < threshold) continue outerLoop; // Skip rest of the row, like those unwanted peas // Process the juicy element } }

And here, our friend continue filters out, without even a blink, the "negative" ones:

int sum = 0; for (int num : numbers) { if (num < 0) continue; // If it's negative, it's not invited to the party sum += num; // Only the "positive" ones get to join the sum party! }

In these examples, continue helped by sifting through unwanted elements and streamlining our process to embrace performance and simplicity.