Java While Loop Examples

The while loop in Java is a control flow statement that repeatedly executes a block of code as long as a given condition is true. It’s particularly useful for situations where you do not know beforehand how many times you need to iterate. Below are examples demonstrating various uses of the while loop, complete with explanations and comments for clarity.

Basic while Loop

A basic while loop example that prints numbers from 1 to 5.

In this example, the loop continues to execute as long as i is less than or equal to 5. The variable i is incremented in each iteration, ensuring the loop eventually terminates.

Infinite while Loop

An infinite loop occurs when the condition never becomes false. Use with caution!

Here, the condition is always true, creating an infinite loop. The break statement is used to exit the loop safely.

while Loop for Reading User Input

The while loop can be used to read user input until a certain condition is met. In this example, it reads input until the user enters “exit”.

Using while Loop for Array Iteration

Although for-each and for loops are more commonly used for arrays, you can use a while loop to iterate through an array.

while Loop with Break and Continue

The break statement can exit a loop, and continue can skip to the next iteration.

In this example, when num is 5, the loop skips printing the number by using continue, and when num reaches 8, it exits the loop with break, preventing 8 from being printed.

The while loop is a versatile tool in Java, offering the flexibility to handle repetitive tasks with dynamic conditions. Through these examples, you can see the wide range of applications for while loops, from simple counting to controlling program flow based on user input or other runtime conditions.

Leave a Reply

Your email address will not be published. Required fields are marked *