Java while Loop

The Java while loop continually executes a block of statements until a particular condition evaluates to true. As soon as the condition becomes false, the while loop terminates.

In simple words, if the number of iterations is not fixed or determined at the start, it is recommended to use the while loop.

1. How while loop works?

While loop
While loop
  • The execution start with evaluation of the condition-expression.
  • If the condition is evaluated to true, statements block is executed. This is called one iteration.
  • An iteration happen everytime the condition is true.
  • When the condition is evaluated to false, the loop is terminated immediately.

2. While loop syntax

The syntax of while loop is:

while (condition-expression) {
     statement(s);
}

The condition-expression must be a boolean expression and the statements can be one simple statement or a block of multiple statements. Everytime the condition-expression evaluates to true, statement(s) block is executed.

The while statement continues testing the condition-expression in loop and executing the block until the condition-expression evaluates to false.

3. While loop example

3.1. Print all numbers from 1 to N

To print all integers between 1 and 5 using a while-loop, we can create a condition on a local variable counter which must not be less than or equal to 5.

As soon as, the counter reaches 6, the loop terminates.

int counter = 1;

while (counter <= 5) 
{
    System.out.println(counter);
    counter++;
}

Program output.

1
2
3
4
5

3.2. Iterating over an arraylist

Java program to iterate over an ArrayList using iterator and while loop.

ArrayList<Integer> list = new ArrayList<>();
        
list.add(1);
list.add(2);
list.add(3);

Iterator<Integer> iterator = list.iterator();

while (iterator.hasNext()) 
{
    System.out.println(iterator.next());
}

Program output.

1
2
3

3.3. Iterating over an array

To iterate over array, we should create the condition on array length. We need to iterate over all array element using the index counter.

Once index reaches is equal to the length of the array, the while loop terminates.

Integer[] idArray = new Integer[] {1,2,3,4,5}; 
int index = 0;

while (index < idArray.length) 
{
    System.out.println(idArray[index]);
    index++;
}

Program output.

1
2
3
4
5

4. Infinite while loop

Programmers makes mistake. If the conditional-expression given in while loop never terminates the the lopp will result into infinite while-loop.

For example, if the index value is not incremented after each iteration, then the condition will never terminate.

In given example, index start with 0 and check if it is less than array length. As we are not incrementing its value, it will always be less than 5, no matter how many iterations happen. This loop is an infinite loop.

The infinite loops, sometimes, result into StackOverflowError or OutOfMemoryError based on what we are trying to do in the loop. If there is no memory leaks or usage, it is possible that the loop never terminates and executes infinitely.

Integer[] idArray = new Integer[] {1,2,3,4,5}; 
int index = 0;

while (index < idArray.length) 
{
    System.out.println(idArray[index]);
}

5. while-loop vs for-loop

Unlike the for-loop statement, the condition-expression in while-loop statement is not optional.

In general, a for-loop statement can be converted to a while-loop statement. However, not all for-loop statements can be converted to a while-loop statement.

5.1. A for-loop statement

for (initialization; condition-expression; expression-list) 
{
    statements
}   

5.2. Equivalent while-loop Statement

initialization;

while (condition-expression) 
{
        statements;
        expression-list;
}

6. while loop with break keyword

A break statement is used to exit the loop in a while-loop statement. We can rewrite the first example using a break statement as follows.

int i = 1;

while (true) // Cannot exit the loop from here
{   
    if (i <= 5) 
    {
        System.out.println(i);
        i++;
    }
    else 
    {
        break; // Exit the loop
    }
}

Simple, right? Practice it more by creating few more programs around while loop control statement.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.