← Back to Chapters

Java while Loop

? Java while Loop

? Quick Overview

The while loop in Java is used to repeatedly execute a block of code as long as a given condition remains true. It is best suited when the number of iterations is not known in advance.

? Key Concepts

  • Entry-controlled loop
  • Condition is checked before execution
  • May execute zero or more times
  • Commonly used with counters and conditions

? Syntax / Theory

? View Code Example
// Basic syntax of while loop in Java
while(condition){
    // statements
}

? Code Example

? View Code Example
// Print numbers from 1 to 5 using while loop
class WhileDemo {
public static void main(String[] args) {
int i = 1;
while(i <= 5) {
System.out.println(i);
i++;
}
}
}

? Live Output / Explanation

Output

1
2
3
4
5

The loop starts with i = 1. As long as i <= 5 is true, the loop runs and increments i by 1 each time.

? Loop Simulator

Set a limit and watch the loop run step-by-step!

int i = 1; while ( i <= )
// Output will appear here...
// Click "Run Code" to start.
Current Value in Memory: i = 1

✅ Tips & Best Practices

  • Always update the loop variable to avoid infinite loops
  • Use while when iterations are uncertain
  • Prefer readable conditions
  • Test boundary conditions carefully

? Try It Yourself

  • Print even numbers from 2 to 20
  • Calculate the sum of first 10 natural numbers
  • Create a loop that stops when a value reaches 100