Last Updated:

While loop in Java

There are several varieties of a loop in Java:

  • while
  • do.. while
  • for
  • foreach

A while loop is called a "preconditioned loop." This means that the condition is first checked in parentheses, and then the body of the loop is executed.

Do.. while is a "loop with a postcondition". This means that the body of the cycle will be executed at least once. After that, the condition will be checked and, depending on its truth, the execution of the loop will either continue or be interrupted.

The for loop has a counter. You can set the initial value of the counter, set the condition to continue the loop, and update it after each iteration. Such a loop is especially convenient when passing through the elements of the array or in cases where the body of the loop needs to be executed a given number of times.

The foreach loop is designed specifically for arrays and collections. It traverses all the elements of the collection and does not require you to explicitly access the array index in code. Here we will consider the first type - the while loop.

While statement in Java

The while loop operator is available in almost all modern programming languages. Of course, Java has it too. This construct allows you to execute the same block of code any number of times. Execution stops if the condition becomes false, or if the code specifies an explicit exit from the loop.

In general, this design looks like this:

while (condition) {
// loop body

}

In this case, the condition must return true or false. As long as it is true, the body of the loop is executed. Once the condition is set to false, the while loop ends.

A simple example of how the while statement works:

int counter = 0;
int sum = 0;

while (counter < 10) {
sum += counter;
counter++;

}

System.out.println(sum); 45

When a normal while loop is executed, the condition is first checked. If it is false, then the body of the cycle will not be executed once:

boolean flag = false;

while (flag) {
System.out.println(will not be executed));

}

Differences between while and do.. while, for, foreach

In addition to while, there are several other types of loops. They are not much different from while, but they have their own interesting features.

Cycle do.. while is very similar to while, but its body must be executed at least once. The do.. while looks like this:

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

This type of loop is used when at least one iteration is required before checks begin. It's called a postcondition operator. An example of such a series:

Scanner in = new Scanner(System.in);
String password;
do {
password = in.nextLine();
} while (!password.equals(«12345»));

Here we use do.. while, because the value of the password variable does not yet exist. It is initialized in the loop. With a normal while, it would first have to assign a meaningless value:

Scanner in = new Scanner(System.in);
String password = «»;
while (!password.equals(«12345»)) {
password = in.nextLine();

}

The change is small, but do.. while allows you to make the code more understandable and logical. Another common type of loop is the for loop. In general, it looks like this:

for (counter; condition; increment)
// cycle body

}

The loop stops when the condition returns false. If it is initially false, then the body of the cycle will not be executed once. An example of a loop that displays the square of each number from 1 to 20:

for (int i = 1, i <= 20; i++) {
System.out.println(i * i);

}

Neither part is mandatory. You can omit all three parts inside the brackets at all - then the for loop will become infinite. To exit it, you will have to use the break statement:

for (;;) {
if (Math.random() > 0.9) break;

}

A foreach loop is a type of for loop. There is no foreach keyword in Java – it's just a convenient name for this type of loop. It is written as follows:

for (variable : collection) {
// loop body

}

This loop goes through all the elements of the collection and sequentially assigns them to a variable. It is important that the type of the variable matches the type of the returned elements.

Example of a foreach loop:

for (int num : numbers) {
System.out.println(num);

}

In the loop above, we output all the numbers from the numbers array to the console. This is a convenient method of going through collections, which does not require creating a separate counter and working with indexes. Moreover, not all collections have indexes.

The collection in this case will be any object that implements the java.lang.Iterable interface. Thus, the while loop has many alternatives. In each situation, you should use the most appropriate loop type to make the code more understandable and easy to work with.

Other features of the while loop

Java has two additional statements to control the execution of the while loop: continue and break. They allow you to move to the next iteration of the loop ahead of schedule or interrupt its execution altogether.

The continue statement allows you to move to the next iteration without having to complete the body of the loop. For example, when enumerating numbers from 1 to 100, you can skip all numbers that are divisible by 3 without a remainder:

int counter = 1;

while (counter < 101) {
if (counter % 3 == 0) {
counter++;
continue;

}

System.out.println(counter++);
}

In turn, the break statement interrupts the execution of the loop altogether. For example, when you enter a certain line in a terminal, you can exit the loop explicitly:

Scanner in = new Scanner(System.in);
String input = «»;
int counter = 0;
while (counter < 100) {
input = in.nextLine();
if (input.equals("stopword")) break;
counter++;

}