While Loop in Java

This loop is basically applied to a program where the number of iterations is not fixed.

The syntax of while loop:

class Repeat
{
    public static void main()
    {
        int i = 1;
        
        while (i <= 8)
        {
            System.out.println("I Love Computers");
            i++;
        }
    }
}

Output:

I Love Computers
I Love Computers
I Love Computers
I Love Computers
I Love Computers
I Love Computers
I Love Computers
I Love Computers

Let us understand what happened:

Step 1) The control variable ‘i’ is declared outside the loop construct and is initialized with the value 1.

Step 2) The while-loop construct starts and the test condition is given as  ‘ i<=8’, which means while the value of i is less than or equals to 8, the loop will execute.

Step 3) The step value is given as ‘i++’ inside the looping block, which means i=i+1, i.e. the value of i is incremented by 1 at every iteration till the test condition is true.

Step 4) The statement inside the block is executed until the condition is true.

Similarly, let’s write a program to print the first ten multiples of 2, but this time using while loop:

class Multiple
{
    public static void main()
    {
        int i = 1;
        int c = 0;
        while (i <= 10)
        {
            c = 2 * i;
            System.out.println(c);
            i++;
        }
    }
}

Output:

2
4
6
8
10
12
14
16
18
20
While Loop in Java