Break Statement In Java

Break Statement In Java

As the name of the keyword says, the break keyword is used for breaking out of the loop usually. If you are familiar with the concept of switch statements, you might have seen this break keyword there as well. Here, we are going to use the break keyword in the context of loops.

Sometimes, we might encounter some situation in which we want to move out of the loop for some condition. Like if we run a loop for pin verification of a user giving him/her some chances to enter his/her pin to verify. If the user presses cancel, then we have to break out of the loop however for example. This was just an informal example that we can give a try on.

Break Statement In Java

Again as another example, we can consider that there is an array with some names of people, as elements of the array. Now, let’s say that we iterate through the loop, and we want to break out of the loop as soon as we encounter the name of a person starting with p (I don’t know why would we do that with this person, but still it is ok as an example). So, if we want to do this, we can do it with the help of the break keyword.

Lets now understand the break keyword with help of an example →

I want to again mention that we might encounter some situations where we have to break out of the loop. Now let’s have an example implementation to understand what is the break keyword doing. In the below example, we are iterating from 0 to 9 (10 is not included), and then if the value from the variable becomes 7, we want to break out of them for a loop. (I don’t know why we would do this, but let’s do it!)

public class Loop {
public static void main(String[] args) {
for (int i = 0;i<10;i++){
if (i==7){
System.out.println(“Found the value of i to be 7! breaking out the loop”);
break;
}
System.out.println(“The value of i is : ” + i);
}
System.out.println(“End of the for loop.”);
}
}

Well, if we have a look at the above code, and observe the loop, the basic expectation would be that the loop executes from 0 to 9 right? But here, in the loop for some reason, we need to break out of them

for a loop when the value of the variable i reaches 7. So, if we run the program, we find that the loop starts at 0 as usual and moves through the other values, but as soon as the variable reaches the value of 7, we break out of the loop, and the statement which says end of the for loop prints. But the usual flow of the loop would be starting from 0, going up to 9, and then moving out of the loop.

So, in short, whenever you want to break out of the loop upon some condition, you can use the break keyword to do so. Let’s say that If you are creating some game, for anything, and if the user enters the key q, the game terminates. This is also where you can make use of the break keyword. Just check if the user has entered q, and if the condition is true, just show some message, and then break!

This can prove to be pretty much interesting and useful at times.