HOME HTML EDITOR C JAVA PHP

Java While Loop: Controlled Repetition

Loops are used to execute a block of code repeatedly as long as a specified condition is reached. The while loop is the simplest form of iteration in Java.

Warning: Always ensure that the condition in your loop eventually becomes false. If not, you will create an Infinite Loop, which can crash your application!

1. How the While Loop Works

The while loop loops through a block of code as long as a specified condition is true. It is often called a "pre-test" loop because the condition is checked before the code block runs.

Essential steps in a while loop:

2. Logical Flow

The program enters the loop, checks the condition, executes the body if true, and then jumps back to the top to check the condition again.

3. Difference: while vs do-while

The main difference lies in when the condition is evaluated:

while Loop

Checks condition first. If the condition is false initially, the code never runs.

do-while Loop

Executes code first, then checks condition. The code runs at least once even if the condition is false.

Iteration

Each single execution of the loop body is called one "iteration."

4. When to Use a While Loop

While loops are preferred over for loops in specific scenarios:

  1. Unknown Iterations: When you don't know exactly how many times you need to loop (e.g., reading until the end of a file).
  2. Event Listening: Keeping a program running until a user clicks 'Exit'.
  3. Flag-based Logic: Waiting for a specific boolean state to change.

5. Comparison: Loop Controls

Statement Action Result
break Terminates the loop immediately. Jumps to code after the loop.
continue Skips the current iteration. Jumps back to the condition check.

6. Code Example

int i = 0;
while (i < 5) {
  System.out.println("Count is: " + i);
  i++; // Important: Incrementing the counter
}
// Output: 0, 1, 2, 3, 4

Final Verdict

Mastering the while loop gives you the power to handle dynamic data where the length is not fixed. It is a fundamental building block of logic in Java.

Next: Learn Java For Loop →