0
0
Kotlinprogramming~5 mins

Break and continue behavior in Kotlin

Choose your learning style9 modes available
Introduction

Break and continue help control loops by stopping or skipping parts of the loop. They make your code easier to manage when you want to exit early or skip steps.

When you want to stop a loop as soon as a condition is met, like finding a specific item in a list.
When you want to skip certain steps in a loop, like ignoring invalid data but continuing with the rest.
When searching through data and you want to stop once you get the first match.
When processing user input and you want to skip empty or incorrect entries.
When you want to improve performance by not running unnecessary loop cycles.
Syntax
Kotlin
for (item in collection) {
    if (conditionToStop) {
        break
    }
    if (conditionToSkip) {
        continue
    }
    // other code
}

break stops the whole loop immediately.

continue skips the current loop step and moves to the next one.

Examples
This loop prints numbers 1 and 2, then stops when i is 3.
Kotlin
for (i in 1..5) {
    if (i == 3) break
    println(i)
}
This loop skips printing 3 but prints all other numbers from 1 to 5.
Kotlin
for (i in 1..5) {
    if (i == 3) continue
    println(i)
}
This prints 'heo' by skipping the letter 'l'.
Kotlin
for (char in "hello") {
    if (char == 'l') continue
    print(char)
}
Sample Program

This program shows how break stops the loop when number 4 is reached, so it prints 1, 2, 3 only. Then it shows how continue skips printing 4 but continues printing the rest.

Kotlin
fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    println("Using break:")
    for (num in numbers) {
        if (num == 4) {
            break
        }
        println(num)
    }

    println("Using continue:")
    for (num in numbers) {
        if (num == 4) {
            continue
        }
        println(num)
    }
}
OutputSuccess
Important Notes

Use break carefully because it stops the whole loop immediately.

continue only skips the current step, so the loop keeps running.

Both help make loops more efficient and easier to read.

Summary

break stops the entire loop right away.

continue skips the current loop step and moves on.

Use them to control loops clearly and avoid unnecessary work.