Break Expression

Suppose that you are working with loops. It is sometimes desirable to terminate the loop immediately without checking the test expression. In such case, break is used. It terminates the nearest enclosing loop when encountered (without checking the test expression).

How break works?

Almost always it is used with if..else statements. For example: If expression is evaluated to true, break is executed which terminates the for loop.

 

Example


Output
1
2
3
4

In the code above we have defined the main method with a for and if statement. The for statement iterates through a range from 1 to 10.
When the value of i is equal to 5, expression i == 5 inside if is evaluated to true, and break is executed. This terminates the for loop.

Example: Calculate Sum Until User enters 0


Output
Enter a number: 4
Enter a number: 12
Enter a number: 6
Enter a number: -9
Enter a number: 0
sum = 13

In the above program, the test expression of the while loop is always true. Here the program calculates the sum of numbers entered by the user until user enters 0. The while loop runs until user enters 0. When user inputs 0, break is executed which terminates the while loop.

Labeled break

What you have learned till now is unlabeled form of break, which terminates the nearest enclosing loop. There is another way break can be used (labeled form) to terminate the desired loop (can be outer loop).


Output
Enter a number: 4
Enter a number: 12
Enter a number: 6
Enter a number: -9
Enter a number: 0
sum = 13

Label in Kotlin starts with an identifier which is followed by @.

Here, test@ is a label marked at the outer while loop. Now, by using break with a label (break@test in this case), you can break the specific loop.


Output
i = 1 ; j = 1
i = 1 ; j = 2
i = 2 ; j = 1

Here, when i == 2 expression is evaluated to true, break@first is executed which terminates the loop marked with label first@.

Little variation of the above program

Output
i = 1 ; j = 1
i = 1 ; j = 2
i = 2 ; j = 1
i = 3 ; j = 1
i = 3 ; j = 2
i = 4 ; j = 1
i = 4 ; j = 2

In this program break terminates the loop marked with label @second.

Note: Since, break is used to terminate the innermost loop in this program, it is not necessary to use labeled break in this case.

Questions

I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂

 


 

Follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *