Java While Loop

In Java, the while loop is a fundamental control structure that allows you to repeatedly execute a block of code as long as a specified condition remains true. It provides an efficient way to perform iterative tasks in your programs. In this article, we’ll dive into the world of the while loop, understand its syntax, and explore various use cases with example code.

The Basic while Loop Structure

The while loop has the following syntax:

while (condition) {
    // Code to be executed as long as the condition is true
}
  • The condition is a Boolean expression. As long as this condition evaluates to true, the code block within the loop will continue to execute.
  • The code within the loop is enclosed in curly braces {}.

Example 1: Counting from 1 to 5

Let’s start with a simple example. We’ll use a while loop to count from 1 to 5 and print each number:

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

In this example, we initialize a variable i with 1. The while loop runs as long as i is less than or equal to 5. Inside the loop, we print the value of i and then increment it using i++.

Example 2: User Input Validation

while loops are commonly used for input validation. Here’s an example where we ask the user to enter a positive number, and the loop continues until a valid input is received:

import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number = -1; // Initialize with an invalid value

        while (number <= 0) {
            System.out.print("Enter a positive number: ");
            number = scanner.nextInt();

            if (number <= 0) {
                System.out.println("Invalid input. Please try again.");
            }
        }

        System.out.println("You entered a valid positive number: " + number);
    }
}

In this example, the loop continues until the user enters a positive number (greater than 0).

Example 3: Sum of Numbers

Let’s calculate the sum of numbers from 1 to 100 using a while loop:

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

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

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

The loop runs until n reaches 100, and at each iteration, we add n to the sum variable.

The while loop is a versatile tool in Java, allowing you to create dynamic and efficient solutions for repetitive tasks. Whether it’s counting, input validation, or complex calculations, mastering the while loop is a valuable skill for any Java programmer. Experiment with different conditions and explore its potential in your Java projects.