Java While Loop

Within the realm of programming, loops are essential for executing a series of statements repeatedly until a particular condition is satisfied. The 'while' loop in Java is distinguished for its straightforwardness and adaptability.

What Is while Loop in Java?

The Java while loop is employed to repeat a section of the program multiple times until the specified Boolean condition evaluates to true. When the Boolean condition turns false, the loop terminates automatically.

The while loop functions as an iteration of an if statement. Whenever the number of repetitions is uncertain, it is advisable to employ the while loop.

Syntax pf the Java While Loop

It has the following syntax:

Example

while (condition){    

//code to be executed   

Increment / decrement statement  

}

In this case, the condition refers to a boolean expression that decides if the loop should keep running or stop. The code inside the curly braces will be executed repeatedly as long as the condition remains true.

Parts of while Loop

The components of a while loop consist of:

-

  1. Condition: This is an expression that undergoes testing. If the condition evaluates to true, the loop body is executed, and then the control moves to the update expression. When the condition eventually becomes false, we exit the while loop.

Example:

Example

i <=100
  1. Iteration Expression: This expression adjusts the loop variable each time the loop body is executed.

Example:

while Loop Example

The following example illustrates the fundamental application of a while loop in Java. In this scenario, our objective is to display numbers ranging from 1 to 5:

Example

int i = 1;

while (i <= 5) {

    System.out.println(i);

    i++;

}

Explanation:

In this instance, the iteration commences with the variable i set to 1. The loop evaluates the condition i <= 5 before each cycle, persisting as long as the condition remains valid. During each iteration, the value of i is displayed and subsequently incremented by 1 to ensure the loop's termination and prevent infinite execution.

Java While Loop Flowchart

In the case of a while loop, it is crucial to note that there are instances where it may not even run. When the condition being evaluated turns out to be false, the loop's content is bypassed, and the initial statement following the while loop will be executed.

More Examples on while Loop

In this section, we will explore various instances to illustrate the functionality of the while loop in the Java programming language.

Example 1: Printing Numbers from 1 to 10

In this instance, we are displaying integer values ranging from 1 to 10. In contrast to the for loop, it is essential to initialize and increase the variable employed in the condition (in this case, i) independently. Failing to do so will result in the loop running endlessly.

Example

Example

public class Main {  

public static void main(String[] args) {  

    int i=1;  

    while(i<=10){  

        System.out.println(i);  

    i++;  

    }  

}  

}

Output:

Output

1

2

3

4

5

6

7

8

9

10

Example 2: Finding Factorial of a Number

Consider the following example that illustrates the process of calculating the factorial of a given number by employing a while loop in the Java programming language.

Example

Example

// Java Program to print factorial of 5 using while loop

public class Main {  

    public static void main(String[] args) {  

        // Declare a variable to 5. This is the number whose factorial is to be calculated.  

        int number = 5;  

        // Declare a variable 'factorial' and initialize it to 1. This variable will hold the result of the factorial calculation.  

        int factorial = 1;  

        // Declare a variable 'i' and initialize it to 1.  

        int i = 1;

        //Start a while loop 

        while( i <= number ) {  

            // Multiply the current value of 'factorial' by 'i' and store the result back in 'factorial'.  

            factorial *= i; // This is equivalent to factorial = factorial * i; 

            i++;

        }  

        // Print the calculated factorial to the console.  

        System.out.println("Factorial of " + number + " is: " + factorial);  

    }  

}

Output:

Output

Factorial of 5 is: 120

Java Nested While Loop

A while loop that is placed inside another while loop is known as a nested while loop in the Java programming language. The fundamental structure of a nested while loop is demonstrated as follows:

Syntax of Java Nested While Loop

It has the following syntax:

Example

while (condition){    

 //code to be executed   

 while (condition){    

  //code to be executed   

  Increment / decrement statement  

 }

 Increment / decrement statement  

}

Example 1: Printing Row and Column Values

The following instance showcases the implementation of a nested while loop in Java, wherein the internal loop executes entirely for every iteration of the outer loop.

Example

Example

//Java Program to use nested while loop in Java

public class Main {  

public static void main(String[] args) {  

    int i=1;

    //outer while loop

    while(i<=3){  

        //inner while loop

        int j=1;

        while(j<=5){

            System.out.println(i+" "+j);  

            j++;  

        }  

    i++;

    }

}  

}

Output:

Output

1 1

1 2

1 3

1 4

1 5

2 1

2 2

2 3

2 4

2 5

3 1

3 2

3 3

3 4

3 5

Example 2: Printing Multiplication Table

The following code utilizes a nested while loop to display the multiplication table ranging from 1 to 10 in a well-organized layout.

Example

Example

//Java Program to print multiplication table using while loop in Java

public class Main {  

public static void main(String[] args) {  

    int i=1;

    //outer while loop

    while(i<=10){  

        //inner while loop

        int j=1;

        while(j<=10){

            System.out.print(i*j+" ");  

            j++;  

        }  

        System.out.println();

    i++;

    }

}  

}

Output:

Output

1 2 3 4 5 6 7 8 9 10 

2 4 6 8 10 12 14 16 18 20 

3 6 9 12 15 18 21 24 27 30 

4 8 12 16 20 24 28 32 36 40 

5 10 15 20 25 30 35 40 45 50 

6 12 18 24 30 36 42 48 54 60 

7 14 21 28 35 42 49 56 63 70 

8 16 24 32 40 48 56 64 72 80 

9 18 27 36 45 54 63 72 81 90 

10 20 30 40 50 60 70 80 90 100

Java Infinitive while Loop

Inadvertently, while loops can become infinite if the condition consistently resolves to true. For example, providing true as the condition in a while loop can result in an infinite loop.

Syntax of Java infinitive while Loop

It has the following syntax:

Example

while(true){

//code to be executed

}

The loop will run endlessly as the condition "true" is perpetually satisfied. Hence, it is essential to guarantee that the condition within a while loop eventually evaluates to false to terminate the loop.

Example: Java Inifinitive while Loop

Let's consider an example to illustrate the Java while Loop with no end.

Example

public class WhileExample2 {  

public static void main(String[] args) { 

 // setting the infinite while loop by passing true to the condition

    while(true){  

        System.out.println("infinitive while loop");  

    }  

}  

}

Output:

Output

infinitive while loop

infinitive while loop

infinitive while loop

infinitive while loop

infinitive while loop

ctrl+c

Preventing Infinite Loops

In order to avoid infinite loops, it is crucial to integrate techniques that alter the loop's condition inside the loop's body. One approach is to utilize a variable to manage the loop:

Example

int count = 0;

while (count < 5) {

    System.out.println("Count: " + count);

    count++;

}

In this instance, the loop will run five times, increasing the count variable in each iteration until it reaches 5, meeting the condition and terminating the loop.

Example: prevent infinite loops with a while loop

The illustration below showcases how to avoid endless iterations using a while loop:

Example

public class PreventingInfiniteLoop {

    public static void main(String[] args) {

        int count = 0;

        while (count < 5) {

            System.out.println("Count: " + count);

            count++;

        }

    }

}

Output:

Output

Count: 0

Count: 1

Count: 2

Count: 3

Count: 4

The while loop in Java is a powerful tool that allows programmers to perform repetitive tasks based on a specified condition. Its adaptability and ease of use make it a useful asset in a wide range of programming situations, from basic iteration to intricate input validation processes. It is crucial to avoid infinite loops by guaranteeing that the loop's condition will eventually become false. Proficiency in utilizing and comprehending the while loop is fundamental for Java developers who strive to create effective and dependable code.

Input Required

This code uses input(). Please provide values below: