Java’s While and Do-While Loops in Five Minutes

Share this article

Java’s While and Do-While Loops in Five Minutes

A while loop is a control flow statement that allows us to run a piece of code multiple times. Like loops in general, a while loop can be used to repeat an action as long as a condition is met. The structure of Java’s while loop is very similar to an if statement in the sense that they both check a boolean expression and maybe execute some code.

To be able to follow along, this article expects that you understand variables and arrays in Java. It would also be good if you had some experience with conditional expressions.

While Loop

The while loop is the most basic loop construct in Java. It consists of the while keyword, the loop condition, and the loop body.

while (condition) {
    // loop body
}

A single run-through of the loop body is referred to as an iteration. Before each iteration, the loop condition is evaluated and, just like with if statements, the body is executed only if the loop condition evaluates to true. In fact, a while loop body is repeated as long as the loop condition stays true – you can think of them as if statements where the body of the statement can be repeated.

Usually some execution of the loop will change something that makes the condition evaluate to false and thus the loop ends. A loop with a condition that never becomes false runs infinitely and is commonly referred to as an infinite loop.

Example

int num = 0;
while (num < 10) {
    System.out.println(num);
    num++;
}

This example prints out numbers from 0 to 9. If this seems foreign to you, don’t worry. We’ll go through it step by step.

We first initialize a variable num to equal 0. This will be our loop counter. When the program encounters a while statement, its condition will be evaluated. In our case 0 < 10 evaluates to true and the loop body is executed. Inside the loop body, the num variable is printed out and then incremented by one. Here is where the first iteration ends.

After the first run-through of the loop body, the loop condition is going to be evaluated for the second time. 1 < 10 still evaluates to true and the next iteration can commence. As you can imagine, the same process will be repeated several more times.

The final iteration begins when num is equal to 9. Our loop counter is printed out the last time and is incremented to equal 10. This time, however, a new iteration cannot begin because the loop condition evaluates to false. 10 is not smaller than 10.

As you can see, the loop ran as long as the loop condition held true. Armed with this knowledge, you can create while loops that are a bit more complex, but on the other hand, more useful as well. Let’s iterate over an array.

String[] names = {"Doc", "Dopey", "Bashful", "Grumpy", "Sneezy", "Sleepy", "Happy"};
int index = 0;
while (index < names.length) {
    System.out.println(names[index]);
    index++;
}

The general concept of this example is the same as in the previous one. We initialize a loop counter and iterate over an array until all elements in the array have been printed out. As a matter of fact, iterating over arrays (or Collections for that matter) is a very common use case and Java provides a loop construct which is better suited for that – the for loop.

Do-While Loop

A do-while loop is very similar to a while loop but there is one significant difference: Unlike with a while loop, the condition is checked at the end of each iteration. This means that a do-while loop is always executed at least once.

do {
    // loop body
}
while (condition);

Example

A do-while loop first executes the loop body and then evaluates the loop condition. Based on the result of the evaluation, the loop either terminates or a new iteration is started. To illustrate this idea, let’s have a look at a simple guess my name game.

Scanner scanner = new Scanner(System.in);
String guess;
do {
    System.out.print("Guess my name: ");
    guess = scanner.nextLine();
}
while (!"Daffy Duck".equals(guess));
System.out.println("Congratulations, you guessed my name correctly!");

The example uses a Scanner to parse input from System.in. This is the standard input stream which in most cases corresponds to keyboard input. To put it simply, we’re going to read text typed by the player.

In a guessing game we would like to prompt the player for an answer at least once and do it until the player guesses the correct answer. A do-while loop fits perfectly here. In the loop body we receive input from the player and then the loop condition checks whether it is the correct answer or not. The loop must run as long as the guess does not equal Daffy Duck. If a correct answer is received, the loop terminates and we congratulate the player.

Java's while loop is exiting - but not THAT much

Summary

Loops allow you to repeat a block of code multiple times. This article covered the while and do-while loops in Java. They’re relatively similar in that both check a condition and execute the loop body if it evaluated to true but they have one major difference: A while loop’s condition is checked before each iteration – the loop condition for do-while, however, is checked at the end of each iteration. This means that a do-while loop is always executed at least once.

In addition to while and do-while, Java provides other loop constructs that were not covered in this article. And if you’re interested enough, you can have a look at recursion. Sometimes it’s possible to use a recursive function instead of loops.

Frequently Asked Questions (FAQs) about Java’s While and Do-While Loops

What is the difference between a while loop and a do-while loop in Java?

The primary difference between a while loop and a do-while loop in Java lies in their execution. A while loop first checks the condition before executing the loop body. If the condition is false at the start, the loop body will not execute even once. On the other hand, a do-while loop executes the loop body first and then checks the condition. This means that the loop body of a do-while loop will always execute at least once, regardless of the condition.

How can I break a while loop in Java?

You can break a while loop in Java using the ‘break’ statement. When the ‘break’ statement is encountered within a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop. It can be used to exit a loop prematurely when a certain condition is met.

Can a while loop be used to iterate over an array in Java?

Yes, a while loop can be used to iterate over an array in Java. You would need to initialize a counter variable, use it as the array index, and increment it within the loop. The loop condition would be that the counter is less than the array length.

How can I use a nested while loop in Java?

A nested while loop in Java is a loop within another loop. The inner loop will be executed fully for each iteration of the outer loop. This can be useful for tasks that require repeated operations, such as sorting or searching in multi-dimensional arrays.

What is an infinite loop and how can I avoid it in Java?

An infinite loop in Java is a loop where the condition never becomes false. This results in the loop executing indefinitely, which can cause your program to become unresponsive. To avoid infinite loops, ensure that the loop condition will eventually become false. Also, always have a way to break out of the loop, such as a ‘break’ statement that is executed when a certain condition is met.

Can a do-while loop be used without a condition in Java?

No, a do-while loop cannot be used without a condition in Java. The condition is essential to determine whether the loop should continue executing or stop. Without a condition, the loop would become an infinite loop, which is generally undesirable.

How can I use a while loop to read user input until a valid input is received in Java?

You can use a while loop to read user input until a valid input is received by placing the user input statement inside the loop. The loop condition would be that the input is not valid. If the input is valid, you can use a ‘break’ statement to exit the loop.

What happens if the condition in a do-while loop is always true in Java?

If the condition in a do-while loop is always true, the loop will execute indefinitely, creating an infinite loop. This is generally undesirable as it can cause your program to become unresponsive. To prevent this, ensure that the loop condition will eventually become false.

Can a while loop be used for error checking in Java?

Yes, a while loop can be used for error checking in Java. You can place the code that might cause an error inside the loop, and the loop condition would be that no error has occurred. If an error occurs, you can handle it and continue with the next iteration of the loop.

How can I use a while loop to calculate the sum of a series of numbers in Java?

You can use a while loop to calculate the sum of a series of numbers by initializing a sum variable to 0, and then adding each number to the sum within the loop. The loop condition would be that there are still numbers left to add.

Indrek OtsIndrek Ots
View Author

Software developer, hardware hacker, interested in machine learning, long distance runner.

control flownicolaipquick-tip
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week