Java Break and Continue Statements

🔹 Java Break and Continue Statements

In Java, break and continue are used to control the flow of loops (for, while, do...while).

  • break → Exits the loop completely.

  • continue → Skips the current iteration and moves to the next iteration.


1. Break Statement

The break statement stops the loop immediately.

Example 1: Break in a for loop

public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // loop ends when i is 5
}
System.out.println(i);
}
}
}

📌 Output:

1
2
3
4

Example 2: Break in a while loop

public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
if (i == 7) {
break; // loop ends
}
System.out.println(i);
i++;
}
}
}

📌 Output:

1
2
3
4
5
6

2. Continue Statement

The continue statement skips the current iteration and moves to the next one.

Example 1: Skip a number in for loop

public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // skip when i is 5
}
System.out.println(i);
}
}
}

📌 Output:

1
2
3
4
6
7
8
9
10

Example 2: Skip even numbers

public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
System.out.println(i);
}
}
}

📌 Output:

1
3
5
7
9

3. Break vs Continue

Feature Break Continue
Stops loop Yes, completely No, only current iteration
Moves to next iteration
Common Use Exit on condition Skip unwanted iterations

🔹 4. Nested Loops with Break

public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break; // breaks inner loop only
}
System.out.println("i=" + i + ", j=" + j);
}
}
}
}

📌 Output:

i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=3, j=1
i=3, j=2
i=3, j=3

🔹 5. Nested Loops with Continue

public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue; // skips j=2 in inner loop
}
System.out.println("i=" + i + ", j=" + j);
}
}
}
}

📌 Output:

i=1, j=1
i=1, j=3
i=2, j=1
i=2, j=3

🔹 Summary

Statement Effect Usage
break Stops the loop completely Exit on a specific condition
continue Skips current iteration Skip unwanted elements

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *