Java While Loop


JavaViews 4767

Java while loop is another loop control statement that executes a set of statements based on a given condition. In this tutorial, we will discuss in detail about java while loop. When compared to for loop, while loop does not have any fixed number of iteration. Unlike for loop, the scope of the variable used in java while loop is not limited within the loop since we declare the variable outside the loop.

Java while loop syntax

while(test_expression) {
  //code
  update_counter;//update the variable value used in the test_expression
}

test_expression – This is the condition or expression based on which the while loop executes. If the condition is true, it executes the code within the while loop. If it is false, it exits the while loop.

update_counter – This is to update the variable value that is used in the condition of the java while loop. If we do not specify this, it might result in an infinite loop.

How while loop works

The below flowchart shows you how java while loop works.

Java while loop

 

  • When the execution control points to the while statement, first it evaluates the condition or test expression. The condition can be any type of operator.
  • If the condition returns a true value, it executes the code inside the while loop.
  • It then updates the variable value either increments or decrements the variable. It is important to include this code inside the java while loop, otherwise, it might result in an infinite javawhile loop. We will discuss the infinite loop towards the end of the tutorial.
  • Again control points to the while statement and repeats the above steps.
  • When the condition returns a false value, it exits the java while loop and continues with the execution of statements outside the while loop

Simple java while loop example

Below is a simple code that demonstrates a java while loop.

public class simpleWhileLoopDemo {

  public static void main(String[] args) {
    int i=1;
    while(i<=5) {
      System.out.println("Value of i is: " + i);
      i++;
    }

  }

}
Value of i is: 1
Value of i is: 2
Value of i is: 3
Value of i is: 4
Value of i is: 5

We first declare an int variable i and initialize with value 1. In the while condition, we have the expression as i<=5, which means until i value is less than or equal to 5, it executes the loop.

Hence in the 1st iteration, when i=1, the condition is true and prints the statement inside java while loop. It then increments i value by 1 which means now i=2.

It then again checks if i<=5. Since it is true, it again executes the code inside the loop and increments the value.

It repeats the above steps until i=5. At this stage, after executing the code inside while loop, i value increments and i=6. Now the condition returns false and hence exits the java while loop.

While loop in Array

Similar to for loop, we can also use a java while loop to fetch array elements. In the below example, we fetch the array elements and find the sum of all numbers using the while loop.

public class whileLoopArray {

  public static void main(String[] args) {
    int[] numbers = {20,10,40,50,30};
    int i=0;
    int sum=0;
    while(i<numbers.length) {
      sum = sum+numbers[i];
      i=i+1;
    }
    System.out.println("Sum of array elements: " + sum);
    System.out.println("Length of array: " + i);
  }

}
Sum of array elements: 150
Length of array: 5

Explanation:

First, we initialize an array of integers numbers and declare the java while loop counter variable i. Since it is an array, we need to traverse through all the elements in an array until the last element. For this, we use the length method inside the java while loop condition. This means the while loop executes until i value reaches the length of the array.

Iteration 1 when i=0: condition:true, sum=20, i=1

Iteration 2 when i=1: condition:true, sum=30, i=2

Iteration 3 when i=2: condition:true, sum =70, i=3

Iteration 4 when i=3: condition:true, sum=120, i=4

Iteration 5 when i=4: condition:true, sum=150, i=5

Iteration 6 when i=5: condition:false -> exits while loop

Please refer to our Arrays in java tutorial to know more about Arrays.

Infinite while loop

As discussed at the start of the tutorial, when we do not update the counter variable properly or do not mention the condition correctly, it will result in an infinite while loop. Let’s see this with an example below.

public class infiniteWhileLoop {

  public static void main(String[] args) {
    int i = 0;
    while(i>=0) {
      System.out.println(i);
      i++;
    }

  }

}

Here, we have initialized the variable with value 0. In the java while loop condition, we are checking if i value is greater than or equal to 0. Since we are incrementing i value inside the while loop, the condition i>=0 while always returns a true value and will execute infinitely.

We can also have an infinite java while loop in another way as you can see in the below example. Here the value of the variable bFlag is always true since we are not updating the variable value.

public class infiniteWhileLoop {

  public static void main(String[] args) {
    Boolean bFlag = true;
    while(bFlag) {
      System.out.println("Infinite loop");
    }

  }

}

Hence infinite java while loop occurs in below 2 conditions. It is always important to remember these 2 points when using a while loop.

  • when we do not update the variable value
  • when we do not use the condition in while loop properly

Nested while loop

We can also have a nested while loop in java similar to for loop. When there are multiple while loops, we call it as a nested while loop.

public class Nestedwhileloop {

  public static void main(String[] args) {
    int i=1,j=10;
    while(i<=5) {
      System.out.println("i: " + i);
      i++;
      while(j>=5) {
        System.out.println("j: " + j);
        j--;
      }
    }

  }

}
i: 1
j: 10
j: 9
j: 8
j: 7
j: 6
j: 5
i: 2
i: 3
i: 4
i: 5

In this example, we have 2 while loops. The outer while loop iterates until i<=5 and the inner while loop iterates until j>=5.

When i=1, the condition is true and prints i value and then increments i value by 1. Next, it executes the inner while loop with value j=10. Since the condition j>=5 is true, it prints the j value. Now, it continues the execution of the inner while loop completely until the condition j>=5 returns false. Once it is false, it continues with outer while loop execution until i<=5 returns false.

This is why in the output you can see after printing i=1, it executes all j values starting with j=10 until j=5 and then prints i values until i=5. When i=2, it does not execute the inner while loop since the condition is false.

Java while loop with multiple conditions

We can have multiple conditions with multiple variables inside the java while loop. In the below example, we have 2 variables a and i initialized with values 0. Here we are going to print the even numbers between 0 and 20. For this, inside the java while loop, we have the condition a<=10, which is just a counter variable and another condition ((i%2)==0) to check if it is an even number. Inside the java while loop, we increment the counter variable a by 1 and i value by 2.

public class Whileloopconditions {

  public static void main(String[] args) {
    int a = 0;
    int i = 0;
    System.out.println("Even numbers between 0 to 20:");
    while((a<=10) && ((i%2)==0)) {
      System.out.println(i);
      a++;
      i=i+2;
    }
  }

}
Even numbers between 0 to 20:
0
2
4
6
8
10
12
14
16
18
20

Reference

Translate »