EN
Java - break for loop with condition
1 answers
3 points
How do I break out for loop when some condition is met?
For example:
xxxxxxxxxx
1
public class BreakForLoopExample {
2
3
public static void main(String[] args) {
4
5
for (int i = 0; i < 8; i++) {
6
System.out.println("i: " + i);
7
}
8
}
9
}
Output:
xxxxxxxxxx
1
i: 0
2
i: 1
3
i: 2
4
i: 3
5
i: 4
6
i: 5
7
i: 6
8
i: 7
How to cancel iteration of this for loop when i is equal to 4?
1 answer
1 points
Quick solution:
xxxxxxxxxx
1
public class BreakForLoopExample {
2
3
public static void main(String[] args) {
4
5
for (int i = 0; i < 8; i++) {
6
if (i == 4) {
7
break;
8
}
9
System.out.println("i: " + i);
10
}
11
}
12
}
Output:
xxxxxxxxxx
1
i: 0
2
i: 1
3
i: 2
4
i: 3
We just need to use if condition with break keyword.
xxxxxxxxxx
1
if (i == 4) {
2
break;
3
}
Explanation:
The break keyword statement jumps out of a for loop.
0 commentsShow commentsAdd comment