Skip to content
CampusEduX

Control Flow · Lesson 30 of 150

while Loop

A while loop repeats a block of code as long as a given condition remains true. Unlike a for loop, it doesn't require a fixed count — it simply keeps checking the condition before every repetition.

1 min read

01What is a while Loop?

A while loop repeats a block of code as long as a given condition remains true. Unlike a for loop, it doesn't require a fixed count — it simply keeps checking the condition before every repetition.

02Why is it used?

Some tasks need to repeat until something happens, but you don't know in advance exactly how many times — like asking a user to keep entering numbers until they type "0". A while loop suits this kind of open-ended repetition.

03Real-Life Example

Think of filling a bucket with water: "While the bucket is not full, keep pouring water." You don't count exact pours in advance — you just keep going until the condition (bucket full) becomes false.

04Syntax

java
while (condition) { // code repeats as long as condition is true }

05Example Program

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

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

06Key Points to Remember

  • The condition is checked before the loop body runs even once — if it's false at the start, the body never runs.
  • You must update the variable inside the loop yourself, or the loop may run forever.
  • while is ideal when the number of repetitions isn't known beforehand.