Site icon DataFlair

Java While Loop with Examples

java while loop

Free Java courses with 37 real-time projects - Learn Java

The while loop is a control flow statement in Java that allows code to be executed repeatedly based on a given Boolean condition. The while loop is useful when the number of iterations is not known beforehand.

The while loop enables repetitive execution of a block of code as long as the test condition evaluates to true. Till the condition is false, the loop iterates continuously. Once the condition becomes false, the loop terminates, and the control flow breaks out of the while loop.

The key purpose of the Java while loop is to repeat a set of statements as long as the test condition holds true. The while loop is ideally used when the number of iterations is not predetermined. For example, reading input from the user or file line by line until no lines are left.

The while loop avoids the need to write many repeating if statements to execute code. While an if statement would need to be written multiple times for each iteration, the while loop compactly achieves the same behavior with better readability.

Since the while loop depends on a condition to terminate, it is well-suited for scenarios where the exact number of iterations is unknown and depends on some business logic or external factor. Examples include – polling in multithreaded apps, reading files of variable length, user input loops, etc.

Syntax of the Java While Loop

The syntax of the while loop in Java is straightforward:

while (test_expression)
{
   // statements
 
  update_expression;
}

If the curly braces {} are not used with the while loop, then only the next immediate statement after the loop is considered part of the loop body. For most practical programs, curly braces are included to avoid confusion and define a block of statements for the loop.

Components of the While Loop in Java

1) Test Expression

2) Update Expression

Execution Flow of a Java While Loop

If the condition is true:

If the condition is false:

Examples of While Loops

Let’s look at some examples to understand the usage of while loops.

Example 1: Printing “DataFlair” 5 times

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

Output:
DataFlair
DataFlair
DataFlair
DataFlair
DataFlair

Example 2: Finding the summation of numbers from 1 to 100

public class SumExample {
    public static void main(String[] args) {
        int sum = 0;
        int i = 1;

        while (i <= 100) {
            sum += i;
            i++;
        }

        System.out.println("The sum of numbers from 1 to 100 is: " + sum);
    }
}

Output:
The sum of numbers from 1 to 100 is: 5050

Conclusion

To sum up, Java’s while loops offer several notable features that make them a valuable tool for controlling program flow. These loops operate by repeatedly executing a specified code block as long as a designated test condition remains true, making them ideal for situations where the exact number of iterations is uncertain or depends on dynamic business logic.

The flexibility of the test expression and update expression within while loops provide fine-grained control over the loop’s execution. Their versatility extends to various scenarios such as file processing, user input collection, and thread polling, where their use enhances the overall readability of code and creates a more efficient control flow compared to the repetition of if statements.

Exit mobile version