Learn Java loops step by step. Understand while loops, for loops, loop rules, syntax, and examples with beginner-friendly explanations and clear code samples.
Loops are one of the most powerful concepts in programming. They allow a computer to repeat instructions many times without rewriting code.
Think of loops like telling a student:
βWrite your name 10 times.β
Instead of repeating the instruction 10 times, you give one instruction + a rule.
Without loops:
With loops:
Every loop must have these three parts:
| Step | Name | Purpose | Example |
|---|---|---|---|
| 1 | Initialization | Starting value | int i = 0; |
| 2 | Condition | When to stop | i < 5 |
| 3 | Update | Change value | i++ |
β If update is missing β Infinite loop
π Use a while loop when you donβt know how many times the loop should run.
while(condition){
// code
}
int i = 1;
while(i <= 5){
System.out.println(i);
i++;
}
Output
1
2
3
4
5
int attempts = 1;
while(attempts <= 3){
System.out.println("Try password");
attempts++;
}
Real-life logic:
Keep asking until attempts reach limit.
int i = 1;
while(i <= 5){
System.out.println(i);
}
β Problem: No i++ β condition never changes.
π Use a for loop when you know exactly how many times you want to repeat something.
for(initialization; condition; update){
// code
}
for(int i = 1; i <= 5; i++){
System.out.println(i);
}
for(int i = 2; i <= 10; i += 2){
System.out.println(i);
}
for(int i = 5; i >= 1; i--){
System.out.println(i);
}
System.out.println("Go!");
| Situation | Best Loop |
|---|---|
| Number of repetitions known | for |
| Unknown repetitions | while |
| Condition-based repetition | while |
| Counting numbers | for |
π Rule of thumb for beginners:
If counting β use for If waiting for condition β use while
Task 1 β While Loop Print numbers from 10 to 1.
Task 2 β For Loop Print your name 5 times.
Task 3 β For Loop Print all odd numbers from 1β15.
Task 4 β While Loop Calculate sum of numbers 1β10.
Expected Output:
Sum = 55
Task 5 β For Loop Print multiplication table of 7.
Task 6 β While Loop Print numbers divisible by 3 between 1 and 20.
Task 7 β Pattern Printing
*
**
***
****
*****
Task 8 β Reverse Counting Print numbers from 50 to 0 with step 5.
Task 9 β Guessing Game Logic Keep asking user for number until they enter 7.
(Hint: use while loop)