Kotlin break
In Kotlin, break statement is used to break and jump out of the loop.
Syntax
The syntax of a break statement is
break
where
break
is keyword.
Usually, break statement is placed inside an if-statement, so that the loop can be broken when a specific condition is met.
Examples
1. Break While loop
In the following program, we take a While loop to iterate over numbers from 1 to 10. Also, we will place a break statement inside the loop, to break the While loop after printing 5.
Kotlin Program
fun main(args: Array<String>) {
val n = 10
var i = 1
while (i <= n) {
println(i)
if (i == 5) {
break
}
i++
}
}
Output
1
2
3
4
5
If there is no break statement, the While loop would have printed the numbers upto 10.
2. Break For loop
In the following program, we take a For loop to iterate over a string array. When the string element equals "cherry"
, we shall break the loop using break statement.
Kotlin Program
fun main(args: Array<String>) {
val fruits = arrayOf("apple", "banana", "cherry", "mango", "fig")
for (fruit in fruits) {
if (fruit.equals("cherry")) {
break
}
println(fruit)
}
}
Output
apple
banana
If there is no break statement, the For loop would have printed all the elements in the given string array.