Back to Study Material Java

While Loop in Java

The while loop is the simplest loop in Java. It repeats a block of statements as long as a specified condition remains true. Unlike the for loop, which bun...

While Loop in Java

Condition-Driven Repetition with the While Loop

The while loop is the simplest loop in Java. It repeats a block of statements as long as a specified condition remains true. Unlike the for loop, which bundles initialization and update into the loop header, the while loop only specifies the condition. Initialization happens before the loop, and the update — if needed — must be explicitly placed somewhere inside the loop body.

The syntax is: while (condition) { body }. Before each iteration, the condition is evaluated. If it is true, the body executes. After the body completes, the condition is evaluated again. This continues until the condition becomes false, at which point the loop exits and execution continues with the next statement after the closing brace. If the condition is false before the first iteration, the body never executes at all.

A classic use case for the while loop is reading input until a sentinel value is entered: Scanner sc = new Scanner(System.in); int sum = 0; System.out.print("Enter number (0 to stop): "); int n = sc.nextInt(); while (n != 0) { sum += n; System.out.print("Enter number (0 to stop): "); n = sc.nextInt(); } System.out.println("Sum: " + sum);. The loop continues accumulating a sum until the user enters 0.

Another natural use is implementing algorithms where the number of iterations depends on data at runtime, such as searching for a target in a linked list, reading bytes from a file until end-of-file, or iterating while a mathematical series has not converged to a desired precision.

A loop variable must change inside the body; otherwise the condition will never become false and you have an infinite loop. Ensure the update moves the state toward a condition that will eventually be false. For example, while searching downward: while (index >= 0 && array[index] != target) { index--; }. The index decrements each iteration, guaranteeing the loop eventually terminates.

The while loop is equivalent to a for loop without the initialization and update sections. Choosing between them is a matter of style and clarity: use for when you have a clear initialization, condition, and step in one structure; use while when only the continuation condition is the primary concern.

Interview tip: A classic interview exercise is to convert a for loop to a while loop and vice versa. For (int i = 0; i < n; i++) { body } becomes int i = 0; while (i < n) { body; i++; }. Being able to do this conversion demonstrates understanding of the underlying mechanics of both constructs.