0
0
KotlinHow-ToBeginner · 3 min read

How to Use Break in Kotlin: Simple Guide with Examples

In Kotlin, the break statement is used to immediately exit a loop like for, while, or do-while. When break runs, the program stops the current loop and continues with the code after the loop.
📐

Syntax

The break statement is used inside loops to stop the loop immediately. It has no parameters and is written simply as break.

Use it inside for, while, or do-while loops.

kotlin
while (true) {
    if (someCondition) {
        break
    }
    // other code
}
💻

Example

This example shows a for loop that prints numbers from 1 to 10 but stops when it reaches 5 using break.

kotlin
fun main() {
    for (i in 1..10) {
        if (i == 5) {
            break
        }
        println(i)
    }
}
Output
1 2 3 4
⚠️

Common Pitfalls

One common mistake is using break outside of loops, which causes a compile error because break only works inside loops.

Another pitfall is expecting break to exit multiple nested loops; it only exits the innermost loop.

kotlin
fun main() {
    // Wrong: break outside loop
    // break // This will cause a compile error

    // Nested loops example
    for (i in 1..3) {
        for (j in 1..3) {
            if (j == 2) {
                break // Only exits inner loop
            }
            println("i=$i, j=$j")
        }
    }
}
Output
i=1, j=1 i=2, j=1 i=3, j=1
📊

Quick Reference

  • Use: To exit the nearest enclosing loop immediately.
  • Works with: for, while, do-while loops.
  • Cannot use: Outside loops or to exit functions (use return for that).
  • Nested loops: Only breaks the innermost loop.

Key Takeaways

Use break inside loops to stop the loop immediately.
break only exits the innermost loop when nested.
Do not use break outside loops; it causes errors.
For exiting functions, use return instead of break.
Place break carefully to control loop flow clearly.