Break Statement in Java
Break and Continue Statements
Sometime the programmer wants to skip some conditions in the loop or might desire to terminate the loop without evaluating the test condition.
Break and Continue statements fulfill this same purpose.
What is Break statement in Java ?
A break statement comes in handy when the programmer wants to skip all the statements or condition check following the break keyword. It has two primary uses:
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop. It helps to abruptly terminate the control flow. It is compatible with all forms of loops.
jump statement; break;
Now let us proceed and understand break statement with the help of an example. We want to print a series of numbers but up to a certain limit.
The code for this purpose using for loop and break would be as follows:
In this code we initialize a loop which runs until i <= 10. We want the loop to stop executing when i = 5.
Hence we use the break statement. Let us see what will be the output of the code above.
2 4 6 8
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others