Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java while Keyword
Usage and Examples



while Keyword in Java

The while keyword in Java is used to create a loop that continues executing a block of code as long as a specified condition is true. It’s one of the fundamental looping constructs every Java programmer must master.

Syntax of while Loop

while (condition) {
    // Code to execute repeatedly
}

The loop checks the condition before executing the block. If the condition is false at the beginning, the loop body is skipped altogether.

Flow of Control

  1. Check the condition.
  2. If true, execute the loop body.
  3. Go back and check the condition again.
  4. If false, exit the loop.

Example 1: Simple Counting Loop

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

Explanation: The loop runs as long as count is less than or equal to 5. On each iteration, it prints the value and increments the count by 1.

Example 2: Summing Numbers

public class WhileExample2 {
    public static void main(String[] args) {
        int sum = 0, i = 1;
        while (i <= 10) {
            sum += i;
            i++;
        }
        System.out.println("Sum of first 10 numbers: " + sum);
    }
}
Sum of first 10 numbers: 55

This example demonstrates how we can use a while loop to compute the sum of a sequence of numbers. The logic is simple and readable.

Example 3: Infinite Loop (Be Careful!)

public class WhileExample3 {
    public static void main(String[] args) {
        while (true) {
            System.out.println("This loop will run forever...");
        }
    }
}

Warning: This loop has no exit condition. It's an infinite loop and must be manually stopped.

Use Case: Input Validation

The while loop is especially helpful for validating user input:

import java.util.Scanner;

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

        System.out.print("Enter a number greater than 0: ");
        number = scanner.nextInt();

        while (number <= 0) {
            System.out.println("Invalid input. Try again.");
            System.out.print("Enter a number greater than 0: ");
            number = scanner.nextInt();
        }

        System.out.println("Thank you! You entered: " + number);
    }
}
Enter a number greater than 0: -5
Invalid input. Try again.
Enter a number greater than 0: 0
Invalid input. Try again.
Enter a number greater than 0: 3
Thank you! You entered: 3

Common Mistakes with while Loops

When to Use while Loops

Use a while loop when:


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M