Java While Loop with Examples

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

  • Purpose: To evaluate the condition.
  • Execution of the loop body and moving to the update expression depends on the test_expression.

2) Update Expression

  • Purpose: Incrementing or decrementing the loop variable after executing the loop body.

Execution Flow of a Java While Loop

  • Entry into the while loop.
  • Condition evaluation.
  • Branching based on condition:

If the condition is true:

  • Flow enters the loop body.
  • Statements inside the loop body are executed.
  • Update_expression is executed.
  • Control returns to the test condition for re-evaluation.

If the condition is false:

  • Flow exits the loop.
  • Termination of the while loop (when the condition evaluates to false).

execution flow of a while loop

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

  • Time Complexity: O(n) where n = 5 is the constant number of iterations.
  • Auxiliary Space: O(1) since only two variables i and n are used.

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

  • Time Complexity: O(n) where n = 100 is the constant number of iterations.
  • Auxiliary Space: O(1) since only three variables sum, i and n are used.

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.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *