Loops are the foundation of software programming. Loop enable programmers to perform repetitive tasks such as counting up to a number, displaying a set of web posts, or spawning a power-up in a game. Mastering loops is crucial to becoming a successful programmer.

In this tutorial, we’ll take a look at one of the most common loops used in Java, the Do-While loop. To learn more about the Do-While and other loops, check out this course to learn Java from scratch.

## Understanding Loops

Let’s say you’re a typesetter in the 19th century. For a particular treatise on mathematics, you’ve been tasked with writing down all the even numbers from 0 to 1000. Since computer programming is still a century away, you sit down to list out the numbers, one digit at a time. It’s a painful, thankless job, and you wonder if there isn’t a better way to do it.

If you were tasked with the same job today, you could simply create a very simple program to automate the entire task. Using a simple ‘while’ loop, you can list out the even numbers from 0 to 1000 as*:

```i = 0

while i <= 1000

i = i + 2

print i```

*This program is written in Python, which I’ve used here because its syntax is easier to follow.

The above program simply instructs the computer to keep on adding 2 to the initial value of i (i.e. 0) until it reaches the final value (i <= 1000).

This is the basic structure of virtually every loop: “if condition is true, perform X”.

Did you know that Android apps are written in Java? Check out this course to learn Android programming for Java and make your own apps. You can also try this course on Java essentials for Android to get started.

## The Do While Loop

The do-while loop is one of the most common constructs in programming. Versions of it can be found in virtually every programming language. By itself, the loop is fairly straightforward. It tells the computer: “Do these things as long as these conditions are true”.

There is one crucial difference between the Do-While and While loop. In the While loop, the action is performed only if the condition is true. In the above example, if i is greater than 1000, the condition won’t be fulfilled and the output will be blank.

A Do-While loop, on the other hand, will run at least once because the body (Do) is executed before the condition (While) is tested. This can be expressed as follows:

```do {

something

} while (condition)```

Thus, the something part is always performed at least once before the program moves on to testing the condition provided under While.

In both While and Do-While loops, it is important to note that the condition being tested must eventually return ‘False’ for the loop to close. Otherwise, you’ll end up with an infinite loop, and probably cause a system crash.

## The Do-While Loop in Java

The syntax of the Do-While loop in Java is fairly straightforward. It begins with the keyword “do” then has a block set apart by braces, then the keyword “while” followed by the condition:

```do {

statement1;

statement2; //and so on

} while (condition);```

Notice the ; at the end of while (condition)? Most students tend to leave that out.

This simple program from the official Java tutorials counts to 10:

```class LoopDemo {

public static void main(String[] args) {

int count = 1;

do {

System.out.println(“Count is: “ + count);

count++;

} while (count < 11);

}

}```

In this program, the statement under Do would run at least once before the condition is evaluated. Even if you were to change ‘while(count < 1)’, the output would show at least “Count is: 1”

Let’s see how Do While loop works with an example.

### Example

For this example, you are writing code for a warehouse inventory program. In the warehouse, customer orders are placed on a pallet. Workers add to the pallet while it sits on a scale.  Each pallet should weigh no more than 900 lbs. (408 kg). The scale shows a green light as orders are added to the pallet. When the limit is reached, the green light turns off and a red light turns on. You need to write some code that will cause the lights to change when the weight has reached the limit.

This can be written in words as:

“While the weight on the scale is less than the limit, show the green light. Otherwise show the red light.”

The example below assumes that the functions TurnOnGreenLight(), wait(), and TurnOnRedLIght(), are declared elsewhere. This routine would be launched each time the user pressed a button indicating a new load was being assembled:

```int weight;

int limit = 900;

TurnOnGreenLight();

do {

weight = getweight();

wait(60);

} while (weight < limit);

TurnOnRedLight();```

With this routine, the weight will get checked at least once. The routine checks the weight every 60 seconds. The red light gets turned on when the program leaves the loop.

### Break and Continue in Do-While Loops

• Break: Adding the break command to a program exits the loop immediately irrespective of whether the condition has been met or not. This is very useful in certain situations. For example, if you’re making a game that gives two players three chances to guess a number. Whoever guesses the number first wins. In this case, you’ll need to include ‘break’ to stop the loop when either player guesses the correct number. It is important to remember that if you’re using nested loops, including break will only stop the loop it is in, not the parent loop.

You can add break by inserting {break;} after a condition.

• Continue But what if you want to continue the game after a break? Well, Java has the continue command for that. It works like break, but has the opposite function. You can add it by inserting {continue;} after a condition.

That’s it for our Do-While tutorial. For a more in-depth examination of loops in Java, check out this course on Java fundamentals.

Page Last Updated: October 2013

### Top courses in Java

Java for Beginners
Navin Reddy
4.5 (1,524)
Learn Selenium with Java, Cucumber & Frameworks
Pavan Kumar
4.6 (7,764)
Bestseller
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.7 (4,033)
Bestseller
Oracle Java Certification - Pass the Associate 1Z0-808 Exam.
Tim Buchalka's Learn Programming Academy, Goran Lochert
4.5 (5,832)
Bestseller
Modern Java - Learn Java 8 Features By coding it
Pragmatic Code School
4.5 (11,129)

## Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.