While loop in Java: conditional loop that repeats the code multiple times


Keywords: while loop, conditional loop, iterations sets

Learn programming Java Python

This article will look at the while loop in Java which is a conditional loop that repeats a code sequence until a certain condition is met. We will start by looking at how the while loop works and then focus on solving some examples together.

While loop in Java

The while loop in Java is a so-called condition loop. This means repeating a code sequence, over and over again, until a condition is met. In other words, you use the while loop when you want to repeat an operation as long as a condition is met. Instead of having to rewrite your code several times, we can instead repeat a code block several times. In general, it can be said that a while loop in Java is a repetition of one or more sequences that occurs as long as one or more conditions are met.

The while loop evaluates expression, which must return a boolean value. If the expression evaluates to true, the while loop executes the statement(s) in the code block. The while loop continues testing the expression and executing its block until the expression evaluates to false.

Oracle

How while loop in Java works? 

The while loop is used to iterate a sequence of operations several times. In other words, you repeat parts of your program several times, thus enabling general and dynamic applications because code is reused any number of times. If the number of iterations not is fixed, it’s recommended to use a while loop.

The flow chart in Figure 1 below shows the functions of a while loop

While loop Java Programming

Figure 1: While loop in Java

Let’s break it down

  1. The code sequence begins at Start and then checks if the loop conditions are met.
  2. If the condition is met, true, the program performs the operation. 
  3. When these operations are completed, the code will return to the while condition.
  4. The loop then repeats this process until the condition is false, and then the program continues.

In short, the while loop in java: 

  • Is a loop that repeats a sequence of operations an arbitrary number of times.
  • Repeats the operations as long as a condition is true.
  • Enables general and dynamic applications because code can be reused.
  • Best suited when the number of iterations of the loop is not fixed.

How to create a while loop in Java

While loop in Java:

  • You create the while loop with the reserved word while, followed by a condition in parentheses ( )
  • Within the curly brackets, { }, you specify all operations that you want to execute as long as the condition is true
  • The loop repeats itself until the condition is no longer met, that is, false.

Syntax: Declare while loop in Java

If we use the elements in the list above and insert in the code editor:

while (condition) {
         
      // While loop code block
}

Examples: While loop in Java 

Let’s see a few examples of how to use a while loop in Java.

Example 1: Create a while loop in Java

The following examples show how to use the while loop to perform one or more operations as long a the condition is true.

public class Example{
   public static void main(String[] args) {
   
      int i = 0;                                 

      // As long as the "i" is less than 5, the loop is executed
      while(i < 5){                              
         System.out.println("Hello, World!");    
   
         // Increase the variable each step, i = i + 1
         i++;                                    
      }
   }   
}

Furthermore, in this example, we print Hello, World! as long as the condition is true, in other words, as long as the variable i is less than 5. The program will thus print the text line Hello, World! five times and then end the while loop:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

Note, what would have happened if i++ had not been in the loop? Thats right, since the condition will always be true (zero is always smaller than five), the while loop will never end. The program will then print Hello, World! forever. This is a so-called infinity loop that we mentioned in the article introduction to loops.

If you would like to test the code in the example in an online compile, click the button below.

Example 2: While loop to compare two numbers

In this example we are going to: 

  • Take two numbers, one large that we name large, and one smaller, that we call small. Both numbers are randomly selected to illustrate the example
  • Use a while loop to print the value of both numbers as long as the large number is larger than the small number.
  • For each iteration in the while loop, we will divide the large number by two, and also multiply the smaller number by two.
public static void main(String[] args) {
    int large = 2345;
    int small = 3;

    while (large > small){
        System.out.println("Large = " + large + " and " + "Small = " + small);
        large = large / 2;
        small = small * 2;
   }
}

The answer in this example will be

Large = 2345 and Small = 2
Large = 1172 and Small = 4
Large = 586 and Small = 8
Large = 293 and Small = 16
Large = 146 and Small = 32
Large = 73 and Small = 64

Example 3: While loop using a random number

Let’s take a look at a third and final example. In this example, we will use the random class to generate a random number. If you do not remember how to use the random class to generate random numbers in Java, you can read more about it here.

What we want our program to do is:

  • Generate a random number between 0 – 15.
  • While that number is not equal to 12, the currently generated random number should be printed, as well as how far the current number is from 12 in absolute numbers.
  • Finally, once we have reached the number 12, the program should end by printing out how many iterations it took to reach the target value of 12.
// Import the Scanner class
import java.util.Random;

public class exempel {
        public static void main(String[] args) {

            // Creates a scanner object
            Random rand = new Random();

            // Creates a random integer
            int randomNum =rand.nextInt(15);
            
            // Variable for number of iterations
            int count = 0;
            
            // As long as the random number is not equal to 12
            while(randomNum != 12){
                
                System.out.println("Number is: " + randomNum +
                ", that is: " + Math.abs(12 - randomNum) + " from target value");
                
                // Update the random number
                randomNum = rand.nextInt(15);
                
                // Increase the counter variable by one
                count ++;

            }
            
            // Print number of iterations 
            System.out.println("Target value reached in: " + count + " iterations");
        }
}

Furthermore, in this case, it will not be easy to print out what the answer will be since we get different answers every time. But it might look something like: 

Number is: 5, that is: 7 from target value
Number is: 4, that is: 8 from target value
Number is: 4, that is: 8 from target value
Number is: 7, that is: 5 from target value
Number is: 8, that is: 4 from target value

Target value reached in: 6 iterations

Why use a while loop in Java? 

The while loop in Java used to iterate over a code block as long as the condition is true. We usually use the while loop when we do not know in advance how many times should be repeated. Furthermore, a while loop will continue until a predetermined scenario occurs. It can happen immediately, or it can require a hundred iterations. So the number of loops is governed by a result, not a number. For example, you can continue the loop until the user of the program presses the Z key, and the loop will run until that happens.

Common errors when using the while loop in Java

  • First of all, you end up in an infinity loop, due to several reasons, but could, for example, be that you forget to update the variables that are in the loop. Note that your compiler will end the loop, but it will also cause your program to crash/shut down, and you will receive an error message.
  • You forget to declare a variable used in terms of the while loop. Remember that the first time the condition is checked is before you start running the loop body.
  • Incorrect with one in the number of iterations, usually due to a mismatch between the state of the while loop and the initialization of the variables used in the condition. A good idea for longer loops and more extensive programs is to test the loop on a smaller scale before.

That was just a couple of common mistakes, there are of course more mistakes you can make

Summary: While loop in Java

A while loop in Java is a so-called condition loop. This means repeating a code sequence, over and over again, until a condition is met. Instead of having to rewrite your code several times, we can instead repeat a code block several times. If the number of iterations not is fixed, it’s recommended to use a while loop.

Syntax: While loop

while (condition) {
         
      // While loop code block
}

FAQ: While loop in Java

What is the condition of the while loop?

The expression that the loop will evaluate. As long as that expression is fulfilled, the loop will be executed. For example, it could be that a variable should be greater or less than a given value.

Can you use the while loop even if you know the number of iterations?

Yes, of course. It is possible to set a condition that the while loop must go through the code block a given number of times. But for that purpose, it is usually easier to use the for loop that we will see in the next article.

Can I use a while loop inside another while loop?

Yes, it works fine. Just remember to keep in mind that loops can “get stuck” in an infinity loop so that you pay attention so that your program can move on from the loops.