Java while Loop


Introduction

The while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop is fundamental for performing repeated tasks and is particularly useful when the number of iterations is not known beforehand.

Table of Contents

  1. What is a while Loop?
  2. Syntax of while Loop
  3. How while Loop Works
  4. Simple while Loop Example
  5. Infinite while Loop
  6. while Loop with a Break Statement
  7. while Loop with a Continue Statement
  8. Nested while Loop
  9. Using a while Loop for Input Validation
  10. Conclusion

What is a while Loop?

A while loop repeatedly executes a block of code as long as the specified condition is evaluated as true. It is useful for scenarios where the number of iterations is not predetermined.

Syntax of while Loop

Syntax:

while (condition) {
    // body of loop
}
  • condition: A boolean expression that is evaluated before each iteration of the loop.
  • body of loop: The block of code that is executed as long as the condition is true.

How while Loop Works

  1. The condition is evaluated.
  2. If the condition is true, the body of the loop is executed.
  3. After the body is executed, the condition is evaluated again.
  4. Steps 2 and 3 are repeated until the condition becomes false.
  5. When the condition is false, the loop terminates, and control moves to the next statement after the loop.

Simple while Loop Example

Example:

public class SimpleWhileLoop {
    public static void main(String[] args) {
        int count = 1;
        while (count <= 5) {
            System.out.println("Count: " + count);
            count++;
        }
    }
}

Explanation: This loop prints the numbers from 1 to 5. The condition count <= 5 is checked before each iteration, and the count variable is incremented in each iteration.

Infinite while Loop

An infinite loop occurs when the condition always evaluates to true.

Example:

public class InfiniteWhileLoop {
    public static void main(String[] args) {
        while (true) {
            System.out.println("This is an infinite loop");
        }
    }
}

Explanation: This loop will print "This is an infinite loop" indefinitely because the condition true never changes.

while Loop with a Break Statement

The break statement can be used to exit the loop prematurely.

Example:

public class WhileLoopWithBreak {
    public static void main(String[] args) {
        int count = 1;
        while (count <= 10) {
            if (count == 5) {
                break;
            }
            System.out.println("Count: " + count);
            count++;
        }
    }
}

Explanation: This loop prints numbers from 1 to 4. When count equals 5, the break statement exits the loop.

while Loop with a Continue Statement

The continue statement skips the current iteration and moves to the next iteration of the loop.

Example:

public class WhileLoopWithContinue {
    public static void main(String[] args) {
        int count = 0;
        while (count < 10) {
            count++;
            if (count % 2 == 0) {
                continue;
            }
            System.out.println("Odd number: " + count);
        }
    }
}

Explanation: This loop prints odd numbers from 1 to 9. The continue statement skips the even numbers.

Nested while Loop

A nested while loop is a while loop inside another while loop, useful for iterating over multidimensional structures.

Example:

public class NestedWhileLoop {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 3) {
            int j = 1;
            while (j <= 3) {
                System.out.println("i: " + i + ", j: " + j);
                j++;
            }
            i++;
        }
    }
}

Explanation: This loop prints pairs of i and j values, iterating over all combinations of i and j from 1 to 3.

Using a while Loop for Input Validation

The while loop is often used for validating user input.

Example:

import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number;

        while (true) {
            System.out.print("Enter a positive number: ");
            number = scanner.nextInt();
            if (number > 0) {
                break;
            }
            System.out.println("Invalid input. Please try again.");
        }

        System.out.println("You entered: " + number);
        scanner.close();
    }
}

Explanation: This loop repeatedly prompts the user to enter a positive number until a valid input is provided.

Conclusion

The while loop in Java is a powerful control flow statement for performing repeated tasks based on a condition. Understanding how to use the while loop effectively, including its variations with break and continue statements, as well as nested loops, is essential for writing robust and efficient Java programs.


Comments