āļ‚āđ‰āļēāļĄāđ„āļ›āļĒāļąāļ‡āđ€āļ™āļ·āđ‰āļ­āļŦāļēāļŦāļĨāļąāļ

while Keyword in Java

The while keyword in Java is used to create a loop that executes a block of code as long as a specified condition is true. It is a control flow statement that allows repeated execution of a code block based on a boolean condition.

Usage

The while loop is useful when the number of iterations is not known beforehand and depends on a condition that is evaluated before each iteration.

Syntax

while (condition) {
    // Code to be executed
}
  • condition: A boolean expression that is evaluated before each iteration. If the condition is true, the loop continues; if false, the loop terminates.

Examples

Example 1: Basic while Loop

public class WhileExample {
    public static void main(String[] args) {
        int i = 0;
        while (i < 5) {
            System.out.println("i is: " + i);
            i++;
        }
    }
}

In this example, the variable i is initialized to 0. The while loop continues to execute as long as i is less than 5. The value of i is printed and incremented in each iteration.

Example 2: Reading Input Until Condition is Met

import java.util.Scanner;

public class WhileInputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = "";
        while (!input.equals("exit")) {
            System.out.println("Enter text (type 'exit' to quit): ");
            input = scanner.nextLine();
        }
        scanner.close();
    }
}

This example demonstrates using a while loop to read user input until the user types "exit". The loop continues to prompt the user for input until the condition !input.equals("exit") becomes false.

Example 3: Infinite Loop

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

In this example, the condition in the while loop is true, which means the loop will execute indefinitely. This is known as an infinite loop and should be used with caution.

Tips and Best Practices