While Loop Java Tutorial

Introduction

In this tutorial, we will discuss While Loop Java. As mentioned in the last tutorial, loops are used to run a group of statements repeatedly until a certain condition is met.

Syntax:

while(condition)
{
   statement(s);
}

Flow Execution

The condition is tested first in a while loop, and if it returns true. The statements within the while loop are executed. When the condition returns false, the control exits the loop and moves on to the next line following the while loop.

Note: The important thing to remember when using a while loop is that we must employ an increment or decrement statement inside the loop. So that the loop variable changes on each iteration and the condition returns false at some point. This way, we may end the while loop’s execution; otherwise, the loop would continue forever.

while loop flow

Code Examples

Simple While Loop Java Example

Code 01:

class Main {
    public static void main(String args[]){
         int i=1;
         while(i<10){
              System.out.println(i);
              i++;
         }
    }
}

Output:

1
2
3
4
5
6
7
8
9

Infinite While Loop Java Example

Code 02:

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

This loop will never terminate since it is an endless while loop. This is because the condition is i>1, which is always true because we are incrementing the value of i within the while loop.

Iterating an Array Using While Loop

Using a while loop, we iterate over and display array elements.

Code 03:

class Main {
    public static void main(String args[]){
         int arr[]={1,2,3,4,5};
         //i starts with 0 as array index starts with 0 too
         int i=0;
         while(i<5){
              System.out.println(arr[i]);
              i++;
         }
    }
}

Output:

1
2
3
4
5

FAQs

What is do while loop Java

The Java do-while loop is used to loop through a section of code until the stated condition is met. If the number of iterations is not fixed and the loop must be executed at least once, a do-while loop is advised.

An exit control loop is a Java do-while loop. As a result, unlike the while and for loops, the do-while loop checks the condition at the conclusion of the loop body. Because the condition is tested after the loop body, the Java do-while loop is run at least once.

For vs While Loop

The difference between a for loop and a while loop is that the number of iterations to be done in a for loop is already known and is used to get a certain result. But in a while loop, the command continues until a given condition is met and the assertion is shown to be false.

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

Suggested Articles:

  1. For Loop Java Tutorial

Leave a Comment