Sling Academy
Home/Kotlin/How to Use `break` to Exit Loops in Kotlin

How to Use `break` to Exit Loops in Kotlin

Last updated: November 30, 2024

Loops are fundamental constructs in programming, enabling repetitive execution of code blocks. In Kotlin, similar to other languages, you have the ability to exit loops prematurely using the break statement. This can be useful when a certain condition is met, and you no longer need to continue iterating.

What is the break Statement?

The break statement terminates the current loop iteration and jumps to the next code statement following the loop. It is often used to stop the loop when a specific condition is satisfied.

Using break in a for Loop

Consider the following example where you want to exit a for loop when a specific element is found:

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    for (num in numbers) {
        if (num == 3) {
            println("Number 3 found! Exiting loop.")
            break
        }
        println(num)
    }
}

In this Kotlin code, the loop traverses through a list of numbers. When the number 3 is encountered, the message is printed, and the break statement exits the loop.

Using break in a while Loop

Here's how you can use break in a while loop:

fun main() {
    var count = 0
    while (count < 10) {
        if (count == 5) {
            println("Count is 5, breaking the loop.")
            break
        }
        println(count)
        count++
    }
}

In this case, the program increments the count from 0 to less than 10. When the count reaches 5, it prints a message and the break statement exits the loop prematurely.

Using break in Nested Loops

In nested loops, a break statement applies to the innermost loop. Here’s an example:

fun main() {
    for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) {
                println("Breaking inner loop at i = $i and j = $j")
                break
            }
            println("i = $i, j = $j")
        }
    }
}

When the condition is met in the inner loop (i.e., i == 2 && j == 2), the break statement will only exit the inner loop, allowing the outer loop to continue iterating.

Conclusion

The break statement in Kotlin is a powerful tool for controlling flow within loops, allowing you to terminate loops based on conditions. Use this to optimize your code and create more efficient algorithms.

Next Article: What Does `continue` Do in Kotlin Loops?

Previous Article: How to Use Infinite Loops in Kotlin (and When to Avoid Them)

Series: Control Flow in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin