Low Orbit Flux Logo 2 D

Java How To Exit For Loop

In Java it is incredibly easy to exit or break out of a for loop. We are going to show you how to do this with a very simple, straight forward example.

Quick Answer: To exit or break out of a for loop in Java use the following statement:


break;

Here is a very simple example. We have a for loop that will loop from zero to 99. We break out of this for loop when the counter reaches 25.


import java.util.ArrayList;
  
public class Test1 {
    public static void main( String[] args ){
        for( int c = 0; c < 100; c++ ) {
            if( c == 25 )
                    break;
            System.out.print(c + " " );
        }
    }
}

The output would look like this:


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24