Kotlin Break / Continue
Controlling loop execution flow
🚦 What are Break and Continue?
Break and Continue are control flow statements that change how loops execute. Break exits the loop completely, while Continue skips the current iteration and moves to the next one, giving you precise control over loop behavior.
// Break example
for (i in 1..10) {
if (i == 5) break
println(i) // Prints 1, 2, 3, 4
}
Control Flow Statements
Break
Exit the loop completely
for (i in 1..10) {
if (i == 5) break
println(i)
}
Continue
Skip current iteration, go to next
for (i in 1..5) {
if (i == 3) continue
println(i) // Skips 3
}
Labels
Control nested loops precisely
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) break@outer
}
}
Return
Exit from functions and lambdas
fun search(list: List) {
for (item in list) {
if (item == target) return
}
}
🔹 Break Statement
Exit the loop when a condition is met:
fun main() {
// Find first number divisible by 7
println("Finding first number divisible by 7:")
for (i in 1..50) {
if (i % 7 == 0) {
println("Found it! $i is divisible by 7")
break // Exit the loop
}
println("Checking $i...")
}
// Search in a list
val fruits = listOf("apple", "banana", "orange", "grape", "kiwi")
val searchFor = "orange"
println("\nSearching for '$searchFor':")
for ((index, fruit) in fruits.withIndex()) {
if (fruit == searchFor) {
println("✅ Found '$searchFor' at position $index!")
break
}
println("❌ '$fruit' is not what we're looking for")
}
}
Output:
Finding first number divisible by 7:
Checking 1...
Checking 2...
Checking 3...
Checking 4...
Checking 5...
Checking 6...
Found it! 7 is divisible by 7
Searching for 'orange':
❌ 'apple' is not what we're looking for
❌ 'banana' is not what we're looking for
✅ Found 'orange' at position 2!
🔹 Continue Statement
Skip current iteration and continue with the next:
fun main() {
// Print only even numbers
println("Even numbers from 1 to 10:")
for (i in 1..10) {
if (i % 2 != 0) {
continue // Skip odd numbers
}
println("Even: $i")
}
// Process valid data only
val data = listOf("apple", "", "banana", " ", "orange", "grape")
println("\nProcessing valid data:")
for ((index, item) in data.withIndex()) {
if (item.isBlank()) {
println("Skipping empty item at index $index")
continue
}
val processed = item.trim().uppercase()
println("Processed: '$item' → '$processed'")
}
}
Output:
Even numbers from 1 to 10:
Even: 2
Even: 4
Even: 6
Even: 8
Even: 10
Processing valid data:
Processed: 'apple' → 'APPLE'
Skipping empty item at index 1
Processed: 'banana' → 'BANANA'
Skipping empty item at index 3
Processed: 'orange' → 'ORANGE'
Processed: 'grape' → 'GRAPE'
🔹 Nested Loops with Labels
Control which loop to break or continue:
fun main() {
// Without labels - only breaks inner loop
println("Without labels:")
for (i in 1..3) {
println("Outer loop: $i")
for (j in 1..3) {
if (j == 2) {
println(" Breaking inner loop at j=$j")
break
}
println(" Inner loop: $j")
}
}
// With labels - can break outer loop
println("\nWith labels:")
outer@ for (i in 1..3) {
println("Outer loop: $i")
for (j in 1..3) {
if (i == 2 && j == 2) {
println(" Breaking outer loop at i=$i, j=$j")
break@outer
}
println(" Inner loop: i=$i, j=$j")
}
}
println("Program continues...")
}
Output:
Without labels:
Outer loop: 1
Inner loop: 1
Breaking inner loop at j=2
Outer loop: 2
Inner loop: 1
Breaking inner loop at j=2
Outer loop: 3
Inner loop: 1
Breaking inner loop at j=2
With labels:
Outer loop: 1
Inner loop: i=1, j=1
Inner loop: i=1, j=2
Inner loop: i=1, j=3
Outer loop: 2
Inner loop: i=2, j=1
Breaking outer loop at i=2, j=2
Program continues...
🔹 Practical Examples
Real-world usage scenarios:
fun main() {
// Password validation with attempts limit
val correctPassword = "secret123"
val maxAttempts = 3
var attempts = 0
while (attempts < maxAttempts) {
attempts++
// Simulating user input
val password = when (attempts) {
1 -> "wrong"
2 -> "incorrect"
3 -> "secret123"
else -> ""
}
println("Attempt $attempts: Entered '$password'")
if (password == correctPassword) {
println("✅ Access granted!")
break // Exit the loop on success
}
if (attempts == maxAttempts) {
println("🔒 Account locked after $maxAttempts failed attempts!")
break
}
println("❌ Wrong password, try again!")
}
// Processing numbers with conditions
println("\nProcessing numbers 1-15:")
for (num in 1..15) {
// Skip multiples of 3
if (num % 3 == 0) {
println("Skipping $num (multiple of 3)")
continue
}
// Stop at first number greater than 12
if (num > 12) {
println("Stopping at $num (greater than 12)")
break
}
println("Processing: $num")
}
}
Output:
Attempt 1: Entered 'wrong'
❌ Wrong password, try again!
Attempt 2: Entered 'incorrect'
❌ Wrong password, try again!
Attempt 3: Entered 'secret123'
✅ Access granted!
Processing numbers 1-15:
Processing: 1
Processing: 2
Skipping 3 (multiple of 3)
Processing: 4
Processing: 5
Skipping 6 (multiple of 3)
Processing: 7
Processing: 8
Skipping 9 (multiple of 3)
Processing: 10
Processing: 11
Skipping 12 (multiple of 3)
Stopping at 13 (greater than 12)
🔹 Return in Loops
Exit from functions using return:
fun findFirstEven(numbers: List): Int? {
println("Searching for first even number...")
for (num in numbers) {
println("Checking $num")
if (num % 2 == 0) {
println("Found even number: $num")
return num // Exit function immediately
}
}
println("No even number found")
return null
}
fun processItems(items: List) {
println("Processing items:")
for (item in items) {
if (item == "STOP") {
println("Stop command received, ending processing")
return // Exit function
}
if (item.isBlank()) {
println("Skipping empty item")
continue
}
println("Processing: $item")
}
println("All items processed")
}
fun main() {
val numbers = listOf(1, 3, 5, 8, 9, 10)
val result = findFirstEven(numbers)
println("Result: $result\n")
val items = listOf("apple", "banana", "", "STOP", "orange")
processItems(items)
}
Output:
Searching for first even number...
Checking 1
Checking 3
Checking 5
Checking 8
Found even number: 8
Result: 8
Processing items:
Processing: apple
Processing: banana
Skipping empty item
Stop command received, ending processing