← Back to Kotlin Course | Chapter 3: Control Flow | Lesson 6 of 7

break, continue, and Labels

break and continue let a loop stop early or skip ahead, and labels let you aim those commands at a specific outer loop by name.

Using break

break immediately exits the loop it is inside, skipping any remaining iterations, and execution continues with the code right after the loop.

Example: Using break

markup
fun main() {
    for (i in 1..10) {
        if (i == 5) break
        println("i = $i")
    }
    println("Loop exited")
}

Using continue

continue skips the rest of the current iteration's body and jumps straight to the next iteration's condition check.

Example: Using continue

markup
fun main() {
    for (i in 1..5) {
        if (i % 2 == 0) continue
        println("Odd number: $i")
    }
}

Labeling a Loop

Writing name@ directly before a loop gives it a label, which can then be targeted by break@name or continue@name from inside a nested loop.

Example: Labeling a Loop

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

Breaking an Outer Loop

A labeled break@name inside nested loops exits the specifically named outer loop entirely, rather than just the innermost one.

Example: Breaking an Outer Loop

markup
fun main() {
    search@ for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) break@search
            println("Checking i=$i, j=$j")
        }
    }
    println("Search finished")
}
Common Mistakes
  1. Assuming a plain break inside a nested loop exits all surrounding loops, when it only exits the innermost one unless a label is used.
  2. Forgetting the @ symbol when defining or referencing a label, such as writing loop instead of loop@.
  3. Overusing labeled breaks/continues where restructuring the loops or extracting a function would be clearer.
Chapter Summary
  • break exits the nearest enclosing loop immediately; continue skips to the next iteration of it.
  • A label is written as name@ before a loop, and referenced as break@name or continue@name.
  • Labeled break/continue let you control an outer loop from inside a nested one.
  • Without a label, break/continue only affect the innermost loop they are written in.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.