While Loop & Do…While Loop: Java Basics

Athena Ozanich
Athena Ozanich


One of the most common tasks in any language is managing different data collections. One popular way to do this is to iterate through individual software entries one at a time with a loop. Loops are so popular that the developers and maintainers of these languages have created multiple types of loops. As a result, the commonality of repetitive tasks in software becomes a more straightforward task with loops to help.

Young woman studying Java While loops for her software development course.

This post will cover a particular type of loop called the while loop. You will learn what a while loop is, how it differs from other loops and how to use them. In addition, you will learn about the various ways to use a while loop in your programming. You will also learn the syntax and behavior of while loops with code examples of some popular and practical uses.

You can use the jump links below to help navigate the post.

Let’s get this started.

Download Now: 25 Free HTML & CSS Hacks

Java While Loop

Loops are robust and come in many flavors; the most commonly used loop is the for loop. The for loop takes an initializer that indicates its start point and a conditional limiter that identifies its iteration limit. The loop steps into its next iteration on each passing condition evaluation and thus moves closer to its limit. This behavior differs from a while loop which only accepts a conditional statement.

While loops have similarities to other loops but they also have a unique behavior that sets them apart. For example, unlike the for loop, a while loop does not require a known endpoint, making it more suited to performing specific tasks. As a developer, there will be times when you are working with consistently growing data, making it difficult to determine its size.

The while loop does not care about size; it only cares if the provided condition evaluates true or false. Most loops in any language require a passing — commonly called “truthy” — to continue running its logic. The primary difference here is in the limitations of other loops; a while loop has no maximum number of iterations as long as the condition is true.

Now that we’ve covered what separates a while loop from the rest of them, let’s discuss some common uses.

What is a Java While Loop?

There are several practical uses for while loops, and to cover them all would take a very long time. So instead, let's look at a few of the most common cases to help paint an accurate picture of how useful they are.

  • Data Organization
  • Algorithmic Tasks
  • Data Entry
  • Authentication
  • Penetration Testing
  • IT Security

There are many other tasks that a software program may need to complete repetitively, but not all will have a known endpoint. For example, let’s consider a data entry program that tracks all new signups and adds the user information to a database. With a for loop, it would need to know the maximum number of entries before the loop begins. However, this concern is a null point with a while loop because it can run as long as entries are processed.

Now that we’ve covered a few practical uses for the while loop and discussed one example in detail let's see what that example could look like in code.

Java While Loop Example

Let's look at an example of the code for the above data entry example in its most basic form. A simple while loop that uses an index to track the number of times it has run and runs for the entire length of the provided data. Check out the video below to learn more about how a while loop works in Java.


In this case, the data will be in a complex array, containing elements of many different data types and even an object to store the data provided.

Let's start by looking at the array data first.

String[ ][ ] newPlayers =
      "Username: Stronk",
      "playtime: 00:00:00",
      "Username: SlaysItQueen",
      "playtime: 00:00:00",

This data is a string array and contains only two entries, each of them is an array with three elements. Now that the information is ready, it’s time to create the while loop and proceed, presuming the standard Java file setup.

int index = 0;
while(index < numbers.length) {

The above while loop uses an int variable outside the loop that assigns a starting value of zero. When the while loop begins, it uses this variable to identify the current iteration count and compare it to the array's length. The loop will run as long as the current iteration count is less than the length. This works well since the array index starts at zero; the size will be one item longer than the maximum index.

A two-item array will have a maximum length of two and a maximum index of 1, zero inclusive. In short, it means that the maximum index of the array will always be one less than its length. This condition used with the while loop provides a means to perform this function no matter how large the array could get.

You might use this loop within a function in a practical live scenario. Then call the function at each new signup, and you could set up some code to check for existing entries. The while loop could then run on a new array of unentered elements entered. This setup would create a fast and efficient method of adding new signups to a database.

Now that we’ve discussed the while loop, let's look at its slightly different counterpart, the do while loop.

Do While Loop Java

The do while loop is very similar to the while loop with one distinct difference. So let's discuss the specific behavior that separates them from each other.

The while loop checks the condition first, and if it returns true, the code within it runs. The loop continues until the condition provided returns false, then stops. Alternatively, the do while loop runs its code once before checking the condition and runs again only if the condition is true. This continues until the condition check returns false, then it stops before the next loop starts.

What is a Do While Loop in Java?

There is a precedence for specific tasks needing to run at least once in software development. This behavior provides a unique angle that you cannot replicate with only a while loop.

Sticking with the data entry example above, you could use a do while loop to handle the same task while providing a good user experience. With the do while loop, we can take the case of no new entries to add and provide the user with an informative message.

Java Do While Loop Example

Suppose you were to attempt the same task from above; you would get a different behavior within a do while loop. So let's take the same data entry example suggested above, but this time with no data. This next video will help grease the wheels before we look at a do while code snippet of our hypothetical example from above.


Now let's look at a code snippet of the example discussed earlier.


String[ ][ ] newPlayers= { };

In this case, when the do while loop starts, it will run once no matter what.

String[ ] authedPlayer = new String[ ];
boolean moreEntries = true;
   if(authedPlayer.length === 0){
      console.log("Sorry, no players available.")
   if(authedPlayer.length < newPlayers.length){
      console.log(`${authedPlayer.length} players available.`)
      moreEntries = false;

The code within the do while loop above will run once even though there is no data, and as a result, you can send a message to the user to let them know there are no entries. However, running the same code within a while loop would fail and not execute the code block within the loop.

That’s about it on while and do while loops. Next, let’s do a quick recap and wrap up this post.

Getting Started Using While and Do While loops in Java

In this post, you’ve learned a lot about the two types of while loops and how they differ from other kinds of loops. You’ve learned how to use them and maximize the benefits of their unique behavior. You’ve also learned how they differ, giving you the ability to decide which type of loop will suit which purposes. The best thing to do is play with them and use them in different ways, such as in functions, if statements, and more. The more you use them in different ways, the better you understand how to use them.

New Call-to-action

Topics: Java

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about HTML and CSS and how to use them to improve your website.