Skip to content

Q 34 - break, continue & return #39

Discussion options

You must be logged in to vote

🔄 break

  • Purpose: Immediately exits a loop or switch block.
  • Use case: When a certain condition is met and you want to stop the loop right away.
for (int i = 0; i < 10; i++) {
    if (i == 5) break; // Loop stops here
    System.out.println(i);
}

continue

  • Purpose: Skips the current iteration and moves to the next one.
  • Use case: To ignore specific conditions but keep looping.
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) continue; // Skip even numbers
    System.out.println(i);
}

🔚 return

  • Purpose: Exits from a method and optionally returns a value.
  • Use case: When you’ve got your result or hit an error—end the method there.
int add(int a, int b) {
    return a + b; // Method…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by HARSHITH-MV
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants