Clean β’ Professional
Loops in Java are powerful, but sometimes you need to control their execution. Thatβs where break and continue come in. Weβll also cover pattern programming examples, which are commonly asked in interviews.
Syntax :
break;
β€ Flowchart for Break Statement
βββββββββββββββ
β Start Loop β
ββββββββ¬βββββββ
β
βββββββββββββββββ
β Condition met? β
ββββββββ¬βββββββββ
Yes β No β
βββββββββββββββββ β
β break β Exit β β
β from loop β β
βββββββββββββββββ β
β
Next iterationfor (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // exit loop
}
System.out.println(i);
}
Output:
1
2
3
4
continue;
β€ Flowchart for Continue Statement
βββββββββββββββ
β Start Loop β
ββββββββ¬βββββββ
β
βββββββββββββββββ
β Condition met? β
ββββββββ¬βββββββββ
Yes β No β
ββββββββββββββββββββββ
β continue β Skip β
β current iteration β
ββββββββββββββββββββββ
β
Next iterationfor (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // skip this iteration
}
System.out.println(i);
}
Output:
1
2
3
4
6
7
8
9
10
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break; // exits inner loop
}
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
β οΈ Tip: For breaking outer loops, use labeled break:
outerLoop:
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2 && j==2) break outerLoop;
}
}
Pattern programming is popular in Java interviews. Letβs look at common patterns.
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
*
* *
* * *
* * * *
* * * * *
int n = 5;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
* * * * *
* * * *
* * *
* *
*
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = n; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= (2*i-1); k++) {
System.out.print("*");
}
System.out.println();
}
Output:
*
***
*****
*******
*********