Break as the name suggests, is used to break out of a loop(i.e. for loop) before its execution is complete.
To make it a little simpler, let us take the below example.
Say you have a for loop that is used to print the numbers from 1 to 5.
public class MyApplication { public static void main(String[] args) { for(int x = 1; x <= 5 ; x++) { System.out.println(x); } } }
But let us say, you want to break out of the for loop, if the value of x is 3. i.e. You want to get out of the loop, right after printing 1, 2 and 3.
And we can achieve it using break statement.
Let us modify the above program using the break statement.
public class MyApplication { public static void main(String[] args) { for(int x = 1; x <= 5 ; x++) { System.out.println(x); if (x == 3) { break; } } } }
And all we have done is placed an if condition, right after the print statement, checking if the value of x is equal to 3. If so we break out of the loop.
if (i == 3) {
break; }
And the break statement helps to get out of the for loop.