Theoretical Paper
- Computer Organization
- Data Structure
- Digital Electronics
- Object Oriented Programming
- Discrete Mathematics
- Graph Theory
- Operating Systems
- Software Engineering
- Computer Graphics
- Database Management System
- Operation Research
- Computer Networking
- Image Processing
- Internet Technologies
- Micro Processor
- E-Commerce & ERP
- Dart Programming
- Flutter Tutorial
- Numerical Methods Tutorials
- Flutter Tutorials
- Kotlin Tutorial
Practical Paper
Industrial Training
Kotlin Return and Jump
There are three jump expressions in Kotlin. These jump expressions are used for control the flow of program execution. These jump structures are:
- break
- continue
- return
Break Expression
A break expression is used for terminate the nearest enclosing loop. It is almost used with if-else condition.
For example:
for(..){ //body of for if(checkCondition){ break; } } for(..){ //body of for if(checkCondition){ break; } }
In the above example, for loop terminates its loop when if condition execute break expression.
Kotlin break example:
fun main(args: Array< String>) { for (i in 1..5) { if (i == 3) { break } println(i) } } fun main(args: Array< String>) { for (i in 1..5) { if (i == 3) { break } println(i) } }
Output:
1 2
In the above example, when the value of i became equal to 3 and satisfy the if condition(i==3) than the break expression execute and terminate for loop.
Kotlin Labeled break Expression
Labeled is the form of identifier followed by the @ sign, for example abc@, test@. To make an expression as label, we just put a label in front of expression.
Kotlin labeled break expression is used to terminate the specific loop. This is done by using break expression with @ sign followed by label name (break@loop).
Kotlin labeled break example
fun main(args: Array< String>) { loop@ for (i in 1..3) { for (j in 1..3) { println("i = $i and j = $j") if (i == 2) break@loop } } } fun main(args: Array< String>) { loop@ for (i in 1..3) { for (j in 1..3) { println("i = $i and j = $j") if (i == 2) break@loop } } }
Output:
i = 1 and j = 1 i = 1 and j = 2 i = 1 and j = 3 i = 2 and j = 1
In the above example, when the value of i became 2 and satisfy the if condition which execute break expression followed by labeled name. The break expression followed by labeled name terminates the body of label identifier.