Kotlin Break and Continue

Kotlin break and continue

In Kotlin, break and continue are jump statements used inside loops to control the flow of execution.


1. break Statement

The break statement is used to terminate (stop) the loop immediately.

Example: break in while Loop

fun main() {
var i = 1

while (i <= 10) {
if (i == 5) {
break
}
println(i)
i++
}
}

Output:

1
2
3
4

Example: break in for Loop

fun main() {
for (i in 1..10) {
if (i == 7) {
break
}
println(i)
}
}

2. continue Statement

The continue statement is used to skip the current iteration and move to the next loop cycle.

Example: continue in while Loop

fun main() {
var i = 0

while (i < 5) {
i++
if (i == 3) {
continue
}
println(i)
}
}

Output:

1
2
4
5

Example: continue in for Loop

fun main() {
for (i in 1..5) {
if (i == 2) {
continue
}
println(i)
}
}

3. Labeled break and continue

Kotlin allows labels to control nested loops.

Labeled break

fun main() {
outer@ for (i in 1..3) {
for (j in 1..3) {
if (i == 2 && j == 2) {
break@outer
}
println("i = $i, j = $j")
}
}
}

Labeled continue

fun main() {
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) {
continue@outer
}
println("i = $i, j = $j")
}
}
}

4. When to Use break and continue

  • Use break when you want to exit the loop early

  • Use continue when you want to skip certain values

  • Use labels for nested loops


Summary

  • break → stops the loop

  • continue → skips current iteration

  • Labels help control nested loops

  • Works with for, while, and do-while

You may also like...