Java while Loops

Jakob Jenkov
Last update: 2024-05-09

The Java while loop is similar to the for loop. The while loop enables your Java program to repeat a set of operations while a certain conditions is true.

The Java while loop exist in two variations. The commonly used while loop and the less often do while version. I will cover both while loop versions in this text.

The Java while Loop

Let us first look at the most commonly used variation of the Java while loop. Here is a simple Java while loop example:

int counter = 0;

while(counter < 10) {

    System.out.println("counter: " + counter);

    counter++;
}

This example shows a while loop that executes the body of the loop as long as the counter variable is less than 10. Inside the while loop body the counter is incremented. Eventually the counter variable will no longer be less than 10, and the while loop will stop executing.

Here is another while example that uses a boolean to make the comparison:

boolean shouldContinue = true;

while(shouldContinue == true) {

    System.out.println("running");

    double random = Math.random() * 10D;

    if(random > 5) {
        shouldContinue = true;
    } else {
        shouldContinue = false;
    }

}

This Java while example tests the boolean variable shouldContinue to check if the while loop should be executed or not. If the shouldContinue variable has the value true, the while loop body is executed one more time. If the shouldContinue variable has the value false, the while loop stops, and execution continues at the next statement after the while loop.

Inside the while loop body a random number between 0 and 10 is generated. If the random number is larger than 5, then the shouldContinue variable will be set to true. If the random number is 5 or less, the shouldContinue variable will be set to false.

Like with for loops, the curly braces are optional around the while loop body. If you omit the curly braces then the while loop body will consist of only the first following Java statement. Here is a Java while example illustrating that:

while(iterator.hasNext())
  System.out.println("next: " + iterator.next()); // executed in loop
  System.out.println("second line");              // executed after loop

In this example, only the first System.out.println() statement is executed inside the while loop. The second System.out.println() statement is not executed until after the while loop is finished.

Forgetting the curly braces around the while loop body is a common mistake. Therefore it can be a good habit to just always put them around the while loop body.

The Java do while Loop

The second variation of the Java while loop is the do while construct. Here is a Java do while example:

InputStream inputStream  =
        new FileInputStream("data/text.xml");

int data;
do {
    data = inputStream.read();

} while(data != -1);

Notice the while loop condition is now moved to after the do while loop body. The do while loop body is always executed at least once, and is then executed repeatedly while the while loop condition is true.

The main difference between the two while loop variations is exactly that the do while loop is always executed at least once before the while loop condition is tested. This is not the case with the normal while loop variation explained in the beginning of this text.

The two variations of the Java while loop come in handy in different situations. I mostly used the first while loop variation, but there are situations where I have used the second variation.

The continue Command

Java contains a continue command which can be used inside Java while (and for) loops. The continue command is placed inside the body of the while loop. When the continue command is met, the Java Virtual Machine jumps to the next iteration of the loop without executing more of the while loop body. The next iteration of the while loop body will proceed as any other. If that iteration also meets the continue command, that iteration too will skip to the next iteration, and so forth.

Here is a simple continue example inside a while loop:

String[] strings = {
    "John", "Jack", "Abraham", "Jennifer", "Ann" };

int wordsStartingWithJ = 0;
int i=0;

while( i < strings.length ) {
    if(! strings[i].toLowerCase().startsWith("j")) {
        i++;
        continue;
    }

    wordsStartingWithJ++;
    i++;
}

Notice the if statement inside the while loop. This if statement checks if each String in the strings array does not start with with the letter j. If not, then the continue command is executed, and the while loop continues to the next iteration.

If the current String in the strings array does start with the letter j, then the next Java statement after the if statement is executed, and the variable wordsStartingWithJ is incremented by 1.

The continue command also works inside do while loops. Here is a do while version of the previous example:

String[] strings = {
    "John", "Jack", "Abraham", "Jennifer", "Ann" };

int wordsStartingWithJ = 0;
int i=0;

do {
    if(! strings[i].toLowerCase().startsWith("j")) {
        i++;
        continue;
    }

    wordsStartingWithJ++;
    i++;
} while( i < strings.length );

Notice that this version of the while loop requires that the strings array has a least one element, or it will fail when trying to index into the array at position 0 during the first iteration of the do while loop.

The break Command

The break command is a command that works inside Java while (and for) loops. When the break command is met, the Java Virtual Machine breaks out of the while loop, even if the loop condition is still true. No more iterations of the while loop are executed once a break command is met. Here is a break command example inside a while loop:

String[] strings = {
    "John", "Jack", "Abraham", "Jennifer", "Ann" };

int wordsStartingWithJ = 0;
int i=0;

while(i < strings.length; ) {
    if(strings[i].toLowerCase().startsWith("j")) {
        wordsStartingWithJ++;
    }

    if(wordsStartingWithJ >= 3) {
        break;
    }
    i++;
}

Notice the second if statement inside the while loop. This if statement checks if 3 words or more have been found which starts with the letter j. If yes, the break command is executed, and the program breaks out of the while loop.

Like with the continue command, the break command also works inside do while loops. Here is the example from before, using a do while loop instead:

String[] strings = {
    "John", "Jack", "Abraham", "Jennifer", "Ann" };

int wordsStartingWithJ = 0;
int i=0;

do {
    if(strings[i].toLowerCase().startsWith("j")) {
        wordsStartingWithJ++;
    }

    if(wordsStartingWithJ >= 3) {
        break;
    }
    i++;

} while( i < strings.length; )

Note that this variation of the while loop requires that the strings array always has at least one element. If not, it will fail during the first iteration of the do while loop, when it tries to access the first element (with index 0) of the array.

Variable Visibility in while Loops

Variables declared inside a Java while loop are only visible inside the while loop body. Look at this while loop example:

int count = 0;

while(count < 10) {
    String name = employees[i].getName();

    count++;
}

After the while loop body has finished executing the count variable is still visible, since the count variable is declared outside the while loop body. But the name variable is not visible because it is declared inside the while loop body. Therefore the name variable is only visible inside the while loop body.

while Loops in Other Languages

For the curious reader, here are links to tutorials about while loop instructions in all the programming languages covered here at Jenkov.com:

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next