In this tutorial, you shall learn about break statement in Kotlin, and how to use break statement in loops, with examples.
Kotlin break statement
Kotlin break statement is used to terminate the enclosing loop, be it While loop, Do-while loop, or For loop.
By default, Kotlin break statement terminates the nearest enclosing loop, but we can specify, via label, which enclosing loop must terminate.
Syntax
The syntax to use a break statement is given below.
break
//or
break@label
- break: a Koltin keyword.
- label: a label assigned to an enclosing loop. You may specify your own label name in place of this.
Examples
The following examples, we will see how to break different loop statements using break statement.
1. Break For loop
In the following program, we take a For loop to print numbers from one to hundred. Also, we write a conditional If-statement inside the loop to break it if the number is five.
Main.kt
fun main() {
for (i in 1..100) {
println(i)
if (i==5) break
}
}
Output
1
2
3
4
5
2. Break While Loop
In the following program, we take a While loop to print numbers from one to hundred. Also, we write a conditional If-statement inside the loop to break it if the number is five.
Main.kt
fun main() {
val n = 100
var i = 1
while(i <= n) {
println(i)
i++
if (i==5) break
}
}
Output
1
2
3
4
3. Break Do-while Loop
In the following program, we take a Do-while loop to print numbers from one to hundred. Also, we write a conditional If-statement inside the loop to break it if the number is five.
Main.kt
fun main() {
var n = 100
var i = 1
do {
println(i)
i++
if (i==5) break
} while(i <= n)
}
Output
1
2
3
4
4. Break specific loop identified by label
In the following program, we take a While loop inside a For loop to print some star pattern, and we break the outer loop labeled with the name loop1, using break statement when a condition is met.
Main.kt
fun main() {
loop1@ for(i in 1..10) {
var k = 0
while (k < i) {
if (i*k > 50) break@loop1
print("*")
k++
}
println()
}
}
Output
*
**
***
****
*****
******
*******
*******
Conclusion
In this Kotlin Tutorial, we learned how to use break statement to terminate a loop.