Languages

Java - break for loop with condition

3 points
Asked by:
Kate_C
2943

How do I break out for loop when some condition is met?

For example:

public class BreakForLoopExample {

    public static void main(String[] args) {

        for (int i = 0; i < 8; i++) {
            System.out.println("i: " + i);
        }
    }
}

Output:

i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7

How to cancel iteration of this for loop when i is equal to 4?

1 answers
1 points
Answered by:
Kate_C
2943

Quick solution:

public class BreakForLoopExample {

    public static void main(String[] args) {

        for (int i = 0; i < 8; i++) {
            if (i == 4) {
                break;
            }
            System.out.println("i: " + i);
        }
    }
}

Output:

i: 0
i: 1
i: 2
i: 3

We just need to use if condition with break keyword.

if (i == 4) {
    break;
}

Explanation:

The break keyword statement jumps out of a for loop.

0 comments Add comment
Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.