do-while loops
The do – while loop works in the same way as the ordinary while loop except that the presence of a do block guarantees that the code will execute at least once, even when the condition of the while expression does not evaluate to true:
var y = 10
do {
y++
Log.i("In the do block and y=","$y")
}
while(y < 10)If you copy and paste this code into one of your apps in the onCreate function, and then execute it, the output might not be what you expect. Here is the output:
In the do block and y=: 11
This is a less-used but sometimes perfect solution for a problem. Even though the condition of the while loop is false, the do block executes its code, increments the y variable to 11, and prints a message to logcat. The condition of the while loop is y < 10, so the code in the do block is not executed again. If the expression in the while condition is true, however, then the code in the do block continues to execute as though it was a regular while loop.