Sunday, 8 June 2025

What’s the Difference Between break and continue in Java?

In loops, sometimes you want to stop everything or skip just one step. That’s where break and continue come in.

Let’s break it down πŸ‘‡

πŸ›‘ break

  • Completely exits the loop.

  • Often used when a certain condition is met and you don’t want to keep looping.

Example:

for (int i = 1; i <= 10; i++) {

    if (i == 5) {

        break;  // Loop ends here

    }

    System.out.print(i + " ");

}

// Output: 1 2 3 4


⏭️ continue

  • Skips just the current step, but keeps looping.

  • Useful when you want to skip a specific case.

Example:

for (int i = 1; i <= 5; i++) {

    if (i == 3) {

        continue;  // Skip 3, but keep looping

    }

    System.out.print(i + " ");

}

// Output: 1 2 4 5


Key Difference
KeywordWhat it does
break              Stops the entire loop
continue           Skips current step, goes to next

 

No comments:

Post a Comment

πŸš€ Top 3 Java Projects Every Beginner Should Build (With Code Ideas)

 Tired of just printing "Hello World"? It’s time to build something real. πŸ’» If you're learning Java and want to stand out, ...