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

πŸ‘¨‍πŸ’» How I Started Learning Java at 15 (and You Can Too)

  When I first heard of Java, I thought it was just something to do with Minecraft mods or Android apps. I didn’t realize it would become my...