do-while loop in Java

In the previous post we talked about while loop in Java, today we are gonna focus on do-while loop which is slightly different from while loop.

The main difference is that the condition of loop execution is checked after the iteration is executed, not before like in while loop. Let’s re-visit the example from while loop:

int i = 0;
while(i < 10){

So here the code is executed, if variable i value satisfies the condition ( i < 10). But what to do, if i variable value should be set inside while loop itself? While loop cannot work in that way, so you need to pre-set some value like we did in the example above, so we can do a check before actually executing our code inside the loop.
do-while loop allows us to an iteration and only in the end we check the condition:

int i;
i = scanner.nextInt();
} while(i < 10);

So in the example, when we start our first iteration, i value is not defined and while loop would not work. But for do-while we first execute the code inside do{} and only then check the condition. In this example, a user should enter i value from the keyboard, we use Scanner class for that. It was not covered yet, but don't worry, we'll have a special post for that.

So you can enter whatever you want as i value, do{} will be executed at least once anyway. And that's the major and only difference between while and do-while loops.

There will be a video on this topic available on YouTube, so stay turned and don't miss it!

Leave a Reply