The break and continue keywords are the very important aspect of control structures in Java. Control Structures are the blocks of programming and consists of loops like for loop, while loop and if-else statements. Both the statements work quite similarly although they have different purposes. Let’s have a look at how they work.
Now as you can see that for loop executes for i=-5,-4,…,4,5. For every value of i, it divides num which equals 100. Now if i=0 and it divides num, what would happen? As expected, the program will crash. So to prevent this, we’re using continue statement. When i reaches 0, the division isn’t performed and instead continue statement is executed which skips the execution of rest of the code of the loop and starts from next iteration i.e. i=1.
The output of this program is:
You can see that loop executes for i=0 to i=5 but when i becomes 4, we use break statement which stops further execution and 4 and 5 are not printed.
Have any query? Feel free to share with us in comments.