Control Statements — Part 9
In this chapter, we will discuss the break statement which is a branch statement.
The branch statements like other control statements allow you to control the execution of the statements. You will get to understand them after writing some example programs.
The following branch statements are frequently used in projects:
- break
- continue
- return
We will show you the most common usage of these branch statements.
We will start with the break statement in this chapter. The continue statement will be discussed in the next chapter and the return statement will be discussed in a later chapter as part of the OOP.
Get rakibul rushel’s stories in your inbox
Join Medium for free to get updates from this writer.
The break and continue branch statements work with for, do-while,
while-do, and for-each statement. The switch statement which is yet to be discussed uses the break statement as part of it. The switch statement will be discussed after understanding the enum type.
Branch Statement — break
Well, we are going to first write a program with a do-while statement. The program asks the user to guess a score which is stored in the program. If the user correctly guesses the score then a congrats message is shown and the program terminates. Otherwise, the program continues to ask you to guess the score until the correct score is guessed. Following is the program:
I am not going to go on explaining the above program. If you read the previous articles it should be pretty easy to understand. Particularly, you can read this chapter to understand the do-while statement.
Now, let us write the same program using the break statement. Following is the program:
Whenever the userScore is equal to the storedScore the break statement is executed. When the break statement is executed the execution gets out of the do-while statement and starts executing from the very next statement which follows the do-while statement. In this case, the statement in line 24 is executed.
Here is the output of the program in Fig 1.2:
So, what the break statement is essentially doing is getting out of the loop. The while-do, do-while, for, for-each all of them considered a loop. As they can execute a bunch of statements (sometimes called the body of a block statement) zero or more times. The bunch of statements in the above program are:
System.out.print("Guess the score: ");
userScore = scanner.nextInt();
if(userScore != storedScore) {
System.out.println("Your guess is wrong.....");
}
else {
break;
}So, using a break statement you can jump out of the loop in which it resides.
In the next chapter, we will explain the continue statement, and nested for statements, and discover a fact about the break statement when used in a nested for statements or loop. The next chapter coming soon.







